Search code examples
javascripthtmlforms

onClick event only triggers once when on a form element


I'm attempting to create a form which toggles accessability features however the onClick event only works once and I'm unsure as to why. Here's my code:

function updateAccessible() {
  if (document.getElementById("font").value === true) {
    console.log("update true")
    document.querySelector(':root').style.setProperty('--font', 'cursive, sans-serif')
  } else {
    console.log("update false")
    document.querySelector(':root').style.setProperty('--font', 'sans-serif')
  }

  document.getElementById("accessibleForm").addEventListener("click", updateAccessible)
}
:root {
  --font: cursive, sans-serif;
}

* {
  font-family: var(--font)
}
<form onclick="updateAccessible()" id="accesibleForm">
  <input type="checkbox" name="font" id="font" checked><label for="font">Use custom font</label>
</form>

<p>Example Text</p>


Solution

  • do this that way:

    • <input type="checkbox" have a checked property with a direct boolean value
    • prefer to use names of form elements childs to access any of them
    • use only one .addEventListener() method
    • prefer to use change event for a checkbox

    const
      Root          = document.querySelector(':root')
    , accesibleForm = document.querySelector('#accesibleForm')
      ;
      
    //            fontChkBx is the element name  
    accesibleForm.fontChkBx.addEventListener('change', (e) =>
      {
      if (accesibleForm.fontChkBx.checked)
        Root.style.setProperty('--font', 'cursive, sans-serif');
      else
        Root.style.setProperty('--font', 'sans-serif');
        
      console.clear();
      console.log('update --> ' + accesibleForm.fontChkBx.checked );
      });
    :root {
      --font: cursive, sans-serif;
    }
    
    * {
      font-family: var(--font)
    }
    <form id="accesibleForm">
      <label>
        <input type="checkbox" name="fontChkBx" checked>
        Use custom font
      </label>
    </form>
    
    <p>Example Text</p>