Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Is anyone knows how to keep my checkbox checked with vanilla?

var checkbox = document.querySelector('.hola');
// localStorage.setItem("vrai","true");
// localStorage.setItem("faux","false");
// var checked = localStorage.getItem("vrai");
// var unchecked = localStorage.getItem("faux");

checkbox.addEventListener('change', () => {
  if(checkbox.checked.toString() === 'true') {
    localStorage.setItem("vrai","true");
  } else if (checkbox.checked.toString() === 'false') {
    localStorage.setItem("faux","false");
  }
})

document.onreadystatechange = function () {
  if (document.readyState == "complete") {
    if (checkbox.checked.toString() === localStorage.getItem("vrai")) {
      checkbox.checked = true;
    } else if (checkbox.checked.toString() === localStorage.getItem("faux")) {
      checkbox.checked = false;
    }
  }
}

2 Answers

Reading over that code I'm left wondering why you're using two different storage keys to store the constants true and false instead of a single storage key to store the state of the checkbox. The way the code is written now, the value for "vrai" is always 'true' and "faux" is always false after they are set, and will always eventually be set as you change the state of the checkbox. Then when you load the page you are essentially saying "if the checkbox is checked, leave it checked, if it is unchecked, leave it unchecked"

Perhaps closer to what you intend:

checkbox.addEventListener('change', () => {
  localStorage.setItem("checkboxState", checkbox.checked.toString());
})

document.onreadystatechange = function () {
  if (document.readyState == "complete") {
    if (localStorage.getItem("checkboxState") === "true") {
      checkbox.checked = true;
    } else {
      checkbox.checked = false;
    }
  }
}

Thanks a lot both of you, I knew i was close, i've seen the probleme more complecated than it is.