Search code examples
javascripthtmlcssfontsonchange

How to change font-weight for every keypress in javascript


I am new to coding and am working on a code for a variable font, that I created, so that every letter you type changes font weight (and gets heavier). I already have a code where all letters get heavier at once, and one where font-size changes but I can't figure out how to rewrite that code, so that not the font-size but the font-weight changes. Thank you in advance for your help!

let initWeight = 101;

document.getElementById("testarea").onkeypress = function(event) {
  myFunction(event.key)
};

function myFunction(letter) {
  initWeight += 50;
  const letterHTML = '<span style="font-size:' + initWeight + 'px">' + letter + '</span>'
  document.getElementById("result").innerHTML += letterHTML
}
  @import {
  https: //static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2}
  @font-face {
    font-family:wf_04476cfbcbfe4a349a33e0080;
    src: url("https://static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2") format("woff2");
    font-weight: 101 900
  }
  div {
    font-family: 'wf_04476cfbcbfe4a349a33e0080', sans-serif;
    font-weight: 101;
    font-size: 100px;
  }
<div class="myInput" id="testarea" contentEditable="true"> insert text </div>
<div id="result" contentEditable="true"></div>


Solution

  • Don't you just mean

    '<span style="font-weight:' + initWeight + '">'
    

    let initWeight = 100;
    
    document.getElementById("testarea").onkeypress = function(event) {
      myFunction(event.key)
    };
    
    function myFunction(letter) {
      const letterHTML = '<span style="font-weight:' + initWeight + '">' + letter + '</span>'
      document.getElementById("result").innerHTML += letterHTML
      initWeight += 100;
    }
      @import {
      https: //static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2}
      @font-face {
        font-family:wf_04476cfbcbfe4a349a33e0080;
        src: url("https://static.wixstatic.com/ufonts/5bda5f_04476cfbcbfe4a349a33e0080a539b44/woff2/file.woff2") format("woff2");
        font-weight: 101 900
      }
      div {
        font-family: 'wf_04476cfbcbfe4a349a33e0080', sans-serif;
        font-weight: 101;
        font-size: 100px;
      }
    <div class="myInput" id="testarea" contentEditable="true"> insert text </div>
    <div id="result" contentEditable="true"></div>