I need to complete a site without using CSS at all.
Every thing goes right but i don't know how to change my font-family with pure JS.
Does anyone know how it is possible to import fonts using JS only?
Thanks!
Now, to import a font, simply add a stylesheet or <style> element to the DOM, which has a font-face rule: var link = document. createElement('link'); link. setAttribute('rel', 'stylesheet'); link.
If you use multiple fonts, it might be tempting to preload every font that you use in every format. However, there are performance tradeoffs to using font preloading. With preload, you're essentially forcing browsers to make a high-priority request for the font URL whether or not it's needed.
You say "pure JS" but most likely you are asking how to do it in the browser environment, which exposes a Document Object Model or DOM. Thus, you can use it with Javascript.
Unless this is a trick homework question, there should be no reason to avoid CSS, since the CSS is always available and that's the proper tool for styling things.
Changing the font-family
of an element is easy:
element.style.fontFamily = "Arial, Sans Serif";
Now, to import a font, simply add a stylesheet or <style>
element to the DOM, which has a font-face
rule:
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,700');
document.head.appendChild(link);
There is no other way to do it currently.
I would suggest using Google's Webfontloader, it's incredibly simple to use:
WebFont.load({
google: {
families: ['Droid Sans', 'Droid Serif']
}
});
Which would allow you to use the massive web font library hosted by google here, without needing to explicitly specify the CSS. You can use custom fonts as well if you're willing to use a style tag or a .css file (or you can inject the @font-face via javascript.) There are other web font providers that work with the Webfontloader, just look on the github page.
If you're interested in learning how to do this manually in javascript, any query on injecting CSS via javascript will sort you, but, that's still technically using CSS. Not sure if this/that is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With