2

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!

11
  • Maybe consider going the pure CSS route: stackoverflow.com/q/44804022/691711 Commented Feb 25, 2019 at 18:12
  • @zero298 Lewis is wanting to change the styles of the body element, not the checkbox itself. Commented Feb 25, 2019 at 18:13
  • Computers do not think. They do one order after another. If you do if(...) you tell the computer to check the checked value of x, after that is done he will continue doing other things. He won't check again (if you aren't telling him to do so) Commented Feb 25, 2019 at 18:14
  • @sean You can still change the style of the body by changing its class Commented Feb 25, 2019 at 18:32
  • So do did you solve your problem? Commented Feb 25, 2019 at 18:50

1 Answer 1

2

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" />

Sign up to request clarification or add additional context in comments.

2 Comments

Just tested it on a blank page and it works flawlessly. The problem is in my project structure, will check it. Thanks!
You need to check 2 things. 1. that the id you are getting is correct. 2. that the element exists at the time you are trying to get it. A couple of ways to do that is by adding the script tag at the end. Add an async attribute to your script tag. Use a setTimeout and get the element after a couple of milliseconds. Run the script after everything is rendered using the DOMContentLoaded event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.