skip to Main Content

font.newFileName is a string of only numbers: '000001101', '000001102', '000001103', so on and so forth.

If font.newFileName in new FontFace and setProperty is prefixed with a letter or changed to a${font.newFileName}, the script works…

...

fontList.forEach(font => {

  const
    ff = new FontFace(font.newFileName, `url('${font.newFilePath.replace(/\/g, '/')}')`),
    fontItem = fontItemTemplate.content.cloneNode(true),
    fontNameElement = fontItem.querySelector('.font-name')

  ff.load().then(
    () => document.fonts.add(ff),
    err => console.error('ERROR:', err)
  )

  fontNameElement.style.setProperty('--font-family', font.newFileName)
  fontNameElement.style.fontFamily = 'var(--font-family)'

  ...

Does anybody know why this is the case?

Also, is there some way to use the font.newFileName values as they are without having to prefix a letter to the front?

2

Answers


  1. The CSS font-family property does not accept font names that start with a number(if unquoted)1.

    To make it work you can put it in quotes. Something like:

    fontList.forEach(font => {
        // ...rest
    
      ff.load().then(
        () => document.fonts.add(ff),
        err => console.error('ERROR:', err)
      )
    
      fontNameElement.style.setProperty('--font-family', `'${font.newFileName}'`);
      fontNameElement.style.fontFamily = 'var(--font-family)'
    
      ...
    });
    

    References:

    1. Valid Font Family names
    2. Font Family property
    3. Examples of valid identifier names*

    * Not related to this post but good to refer

    Login or Signup to reply.
  2. You don’t really need prefixes if you make sure the value is kept a string inside the variable.

    One way (among many) is to add quotes around it

    var FontName = '123';
    
    document.body.style.setProperty('--font-family', "'"+FontName+"'")
    document.body.style.fontFamily = 'var(--font-family)'
    @font-face {
      font-family: "123";
      font-style: normal;
      font-weight: 400;
      src: local("Inconsolata Regular"), local("Inconsolata-Regular"), url(https://css-challenges.com/wp-content/themes/ronneby_child/css/QldKNThLqRwH-OJ1UHjlKGlZ5qg.woff2) format("woff2");
    }
    
    body {
      font-size: 50px
    }
    Hello World
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search