lewislbr
lewislbr

Reputation: 1172

Change styles when checking checkbox with JavaScript

I'm trying (with no success) to create a checkbox that changes some style properties of the body when checked, something like this:

<script>
  const x = document.getElementById('y');
  if (x.checked == true) { 
    document.body.style.setProperty('property', 'value');
  } else {
    document.body.style.setProperty('property', 'value');
  }
</script>

What am I doing wrong? 🤔

Thanks in advance!

Upvotes: 2

Views: 3635

Answers (1)

nick zoum
nick zoum

Reputation: 7285

You need to use an event listener and run that script inside the listener. What you are doing in your code is setting the color once when the script is run, you haven't told the program to check every time the checkbox is changed.

const checkBox = document.getElementById('y');
checkBox.addEventListener("change", updateBackground);
updateBackground();

function updateBackground() {
  document.body.style.backgroundColor = checkBox.checked ? "red" : "blue";
}
<input id="y" type="checkbox" />

You could also just a class instead and change or remove the class name.

const checkBox = document.getElementById('y');
checkBox.addEventListener("change", updateBackground);
updateBackground();

function updateBackground() {
  document.body.className = checkBox.checked ? "" : "blue";
}
body {
  background-color: red;
}

body.blue {
  background-color: blue;
}
<input id="y" type="checkbox" />

Upvotes: 2

Related Questions