1

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);
  }
2
  • Not getting this properly. What is the current behaviour? What is the expected behaviour? Commented Jun 12, 2020 at 17:37
  • @palaѕн Current behavior - Font not changing dynamically because custom font / Expected - Typeface changing Commented Jun 12, 2020 at 17:40

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Yes, indeed I thought so... I always find the document.body.style easy method but I guess I will go with the class option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.