Home > Software engineering >  To keep the checkbox checked once checked while browsing entire website
To keep the checkbox checked once checked while browsing entire website

Time:12-26

I am using the checkbox to toggle the black and dark theme color using HTML, CSS, and JS. I have this code inside my navbar. It is working well. But once refreshed or changed to other pages inside the website, it no longer stays dark.

<div>
  <input type="checkbox"  id="chk" />
  <label  for="chk">
    <i ></i>
    <i ></i>
    <div ></div>
   </label>
</div>

Someone suggested the concept of using local storage and I tried this, but it's not working.

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
});


// for checkbox remained checked

document.getElementById('chk')(function(){
    var test = localStorage.input === 'true'? true: false;
    document.getElementById('chk')('input').prop('checked', test || false);
});

document.getElementById('chk')('input').on('change', function() {
    localStorage.input = document.getElementById('chk')(this).is(':checked');
    console.log(document.getElementById('chk')(this).is(':checked'));
});

Please somebody help me.

PS: I'm not a web developer. I use HTML and CSS from here and there for my blog. I'm using GitHub pages to host my website. https://amatya-aditya.github.io/

CodePudding user response:

There were some issues with the syntax of the JavaScript code. Check below for the updated code.

note: document.getElementById() does not return a function

const chk = document.getElementById('chk');

chk.addEventListener('change', (e) => {
    localStorage.setItem('dark-mode', e.target.checked);
    if ( e.target.checked )
      document.body.classList.add('dark');
    else
      document.body.classList.remove('dark');
    
});

window.addEventListener('load', () => {
    let value = localStorage.getItem('dark-mode');
    document.getElementById('chk').checked = value === 'true' ? true : false;
    if ( value === 'true' )
      document.body.classList.add('dark');
    else
      document.body.classList.remove('dark');
})
  • Related