Nicoletta
Nicoletta

Reputation: 57

Is it possible to dynamically change font to a custom typeface with javascript?

I have been looking around, but seem not to find an answer to it!

I have been trying like so:

document.body.style.fontFamily = "src(url(./webfonts/Compagnon-Bold.woff)";

and so:

document.body.style.fontFamily = "Script";

But with no result. It is also in CSS already:

 @font-face {
  font-family: 'Script';
  src: url(./webfonts/Compagnon-Bold.woff);
  }

Upvotes: 1

Views: 2409

Answers (2)

palaѕн
palaѕн

Reputation: 73896

You can use the new FontFace API for this if you support modern browsers:

Here, in this demo the default font is Roboto and when we click on the button the font for the body is changed to Sriracha font.

document.querySelector("button").addEventListener("click", function() {
  var myfont = new FontFace('Sriracha', 'url(https://fonts.gstatic.com/s/sriracha/v4/0nkrC9D4IuYBgWcI9NbfTwE.woff2) format("woff2")');
  myfont.load().then(function(loadedFont) {
    document.fonts.add(loadedFont);
    document.body.style.fontFamily = 'Sriracha';
  }).catch(function(error) {
    // error occurred
  });
});
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
body {
  font-family: 'Roboto', sans-serif;
}
<button>Change Font</button>
<h2>Almost before we knew it, we had left the ground.</h2>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>

Upvotes: 2

redouglas
redouglas

Reputation: 208

You would likely need to use the font name, not the file: document.body.style.fontFamily = "Compagnon Bold";. That said, you might have better luck (or cleaner code) setting up css classes and toggling those instead of modifying inline styles directly.

Upvotes: 1

Related Questions