Home > Net >  How can I hide header if checkbox in localStorage is checked?
How can I hide header if checkbox in localStorage is checked?

Time:09-21

I have a checkbox that can hide header by pressing on it. I also made it save status in localStorage when checked (so it won't reset after reloading page). But even if it is showing as checked after reloading page and getting status from localStorage - header isn't hidden. Is there a way to make it work?

<div class="new-hide-header"><input id="chck" type="checkbox">
  <label for="chck" class="check-trail">
    <span class="check-handler"></span>
  </label>
</div>

<script>
document.getElementById('chck').onclick = function() {
  divTest = document.getElementById('ast-desktop-header');
  divTest2 = document.getElementById('ast-mobile-header');
  var mq = window.matchMedia("(max-width: 921px)");
  if (mq.matches) {
    // window width is at less than 570px
    if (divTest2.style.display === "none") {
      divTest2.style.display = 'block';
    } else {
      divTest2.style.display = "none";
    }
  }
  // window width is more than 570px    
  else {
    if (divTest.style.display === "none") {
      divTest.style.display = 'block';
    } else {
      divTest.style.display = "none";
      var checkbox = document.getElementById('chck');
      localStorage.setItem('chck', checkbox.checked);
    }
  }
}
</script>

<script>
function load() {
  var checked = JSON.parse(localStorage.getItem('chck'));
  document.getElementById("chck").checked = checked;
}
load();
</script>

CodePudding user response:

Call the onclick function after you set the checked property in load()

Stack snippets don't provide access to localStorage and no header html was provided so the following is a simplified example

const chckbox = document.getElementById('chck')

chckbox.onclick = function() {
  const isChecked = this.checked;
  console.log('isChecked =', isChecked);

}

function load() {
  chckbox.checked = true;
  chckbox.onclick();
}

load()
<input type="checkbox" id="chck">

  • Related