Save page settings when reloading it

Asked

Viewed 76 times

2

Hello, I made a web page with a night mode option through a switch. I wonder if it is possible to store the status of the switch to that person who is on the page when they enter a subpage etc. Currently, whenever I change page it goes back to the initial state.

What I’ve done so far: https://jsfiddle.net/hvj6a0hp/

Made using HTML, CSS and Javascript

  • You can use Cookies

1 answer

1


Create a localStorage with the values "1" for light background and "2" for dark background by adding commented lines down in your code:

mode.addEventListener('change', function() {
  if(mode.checked == true) {
    localStorage.estilo = "2"; // valor para layout escuro
    body.style.setProperty('--bg', 'var(--dark)');
    body.style.setProperty('--text', 'var(--light)');
    body.style.setProperty('--styleback', 'var(--trueback)');
  }
  else {
    localStorage.estilo = "1"; // valor para layout claro
    body.style.setProperty('--bg', 'var(--light)');
    body.style.setProperty('--text', 'var(--dark)');
    body.style.setProperty('--styleback', 'var(--falseback)');
  }
});

Add a "trigger" when the page is fully loaded:

$(window).on("load",function(){
    if(localStorage.estilo == "2"){
        $("#mode").trigger("click");
    }
});

When the page is loaded, the above script will check the value of localStorage and apply the change.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.