Home > Net >  How do I save a CSS class in localstorage?
How do I save a CSS class in localstorage?

Time:12-29

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

CodePudding user response:

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

`

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

`

CodePudding user response:

jquery... $("body"). css("background-color","theColorThatYouNedd");

CodePudding user response:

Your onload function is not correct that's why you are not getting the results.

Use window.load instead-

window.onload = () => {
  // YOUR CODE
};

I would suggest using the onload event on your body element which is the recommended way to handle things on page load-

<body onl oad="checkStorage()">....your elements...</body>

And on Js side, do like this-

function checkStorage() {
  var activestate = localStorage.getItem('activestate'); 
  if(activestate !== ''){       
   box.classList.add('active');
  };
}
  • Related