skip to Main Content

I was trying to style a span attached to a checkbox input with JavaScript. It is working but when refreshing the page on input checked, the applied style is not maintained.

const checkbox = document.querySelector("#new");

checkbox.addEventListener('change', function() {

  if (checkbox.checked) {
    document.querySelector("#newFilter").style.backgroundColor = "#272727";
    document.querySelector("#newFilter").style.color = "#ffffff";
  } else {
    document.querySelector("#newFilter").style.backgroundColor = "#ffffff";
    document.querySelector("#newFilter").style.color = "#272727";
  }

});
<input class="" type="checkbox" id="new" name="new" value="New">
<label class="" for="new" id="">
  <span id="newFilter">English Language</span>
</label>

2

Answers


  1. I don’t see any problem. Styles are applied only when you check / uncheck the checkbox.That’s the logic here. If you refresh the page , the styles will not longer exist.

    Login or Signup to reply.
  2. If you want the styles to persist when you exit or refresh the page you have to store the checkbox’s value somehow. Browsers don’t just store a page’s data as it was left, you have to find a way to retrieve and store data yourself.

    One way to do that is with cookies or local storage. But it’s important to understand first how each of those work and what are the appropriate use cases first.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search