I'm loading in a font using WebFontLoader, and then I set an element's font by doing document.getElementById("my-button").style.fontFamily = "Font I Want"
. This isn't working (the font stays as default), but it's weird because:
document.getElementById("my-button").style.fontFamily = "Arial"
directly into the console in dev tools. However, setting the font to "Font I Want" doesn't have any effect.But again, it works when I set it directly with CSS, so I know that the font is loaded in properly.
What could cause JS to not be able to set the style.fontFamily
of an element to a font that's dynamically loaded in? How can I fix this without using CSS (since the font name is dynamically loaded in from a server)?
Without seeing the network traffic that is happening i only can suggest some possible solutions for your problem:
Use the active callback of WebFontLoader to set the font after it's loaded: WebFontLoader has an active callback that gets called when all fonts have been loaded. You can use this callback to set the font on your element. Here's an example:
WebFont.load({
google: {
families: ['Font I Want']
},
active: function() {
document.getElementById("my-button").style.fontFamily = "Font I Want";
}
});
Wrap the font name in quotes and use a fallback font: It's possible that the font name contains characters that are causing issues when setting the style. To ensure that the font name is treated as a string, wrap it in quotes. Additionally, it's always a good idea to provide a fallback font in case the desired font is not available. See:
document.getElementById("my-button").style.fontFamily = "'Font I Want', sans-serif";
If this also doesn't work make sure that you have actually loaded the font successfully with WebFontLoader. You can check this by opening the Developer Tools and switching to the Network tab. There you should be able to see a network request for the font. Make sure that the status of this request is 200 (OK) and that the font has actually been downloaded.