Changing font-feature-settings with javascript

84 Views Asked by At

I'm trying to activate different stylistic sets, in this example with a button.

My code:

<p id="demo">B</p>

<button type="button" onclick="document.getElementById('demo').style.fontFeatureSettings ='ss01'">Click Me!</button>
3

There are 3 best solutions below

0
On

The issue is, the value ss01 needs to be "ss01" ... in onclick= that's going to get a little messy, though doable like so:

<button type="button"
    onclick="document.getElementById('demo').style.fontFeatureSettings
        ='@quot;ss01@quot;'">
    Click Me!
</button>

(Note: I made it multiline so it's easy to read here)

I would use addEventListener instead for cleaner looking code

document.getElementById("theButton").addEventListener('click', () => {
  document.getElementById('demo').style.fontFeatureSettings ='"ss01"';
});
<p id="demo">B</p>

<button type="button" id="theButton">Click Me!</button>

1
On

1)Have you import the font in your head?

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nome+del+Font">

2)if you want to change only the style you need to write:

document.getElementById('demo').style.fontFamily = "'Roboto', sans-serif";
  1. You can also use the line below to activate a specific set of styles:

    document.getElementById('demo').style.fontFeatureSettings = "'ss01'";

However, please note that not all browsers support all sets of styles, and you should check in the font documentation if the specific set of styles (such as SS01) is included.

0
On

First of All 1 - font-feature-settings work's ONLY on OpenType fonts

Why not simply by changing class values ?

could you point me to an example of how this is done?

const
  myButton = document.querySelector('#my-button')
, p_Dema   = document.querySelector('p#demo')
  ;
myButton.addEventListener('click', () =>
  {
  p_Dema.classList.toggle('fontFeature_Zero');
  });
p  {
    font-family : 'Linux Libertine Display O'; /* OpenType font */ 
    font-size   : 2em;
  font-feature-settings: normal;
  }
 
.fontFeature_Zero {
  font-feature-settings: "zero";
}
<p id="demo"  > 0 - O</p>

<button type="button" id="my-button">Click Me!</button>