Search code examples
javascriptcsslocal-storagesave

How do I save a CSS class in localstorage?


I have an HTML page with a lot of boxes and every box I click I want to apply a new CSS class that changes its background color and save the progress. I'm trying to save this new CSS class in localstorage but i'm doing something wrong. Could someone help me?

the JS code is:

let box = document.querySelector(".box");
let box_1 = document.querySelector(".box-1");
let box_2 = document.querySelector(".box-2");
const next = document.querySelector(".next");


document.onload=(function(){
  var activestate = localStorage.getItem('activestate');  
    if(activestate !== ''){       
        box.classList.add('active');
     };
});

box_1.addEventListener('click', function(){
    box_1.classList.add('active');
    box_2.classList.remove('disabled-link');
    localStorage.setItem('activestate', 'active');   
});

box_2.addEventListener('click', function(){
    if (box_1.classList.contains('active')) {
        box_2.classList.add('active');
        localStorage.setItem('activestate', 'active'); 
        next.style.display = "block";
    };
});

here's the full code in Codepen: https://codepen.io/giuse187/pen/zYLrdMe


Solution

  • Replace "document.onload" with "window.addEventListener"

    `

    window.addEventListener('load', function() {
      var activestate = localStorage.getItem('activestate');  
      if(activestate !== null && activestate !== '') {       
        box.classList.add('active');
      }
    });
    

    `