Save page settings when reloading

2

Hello, I made a web page with a night mode option via a switch. I would like to know if it is possible to store the state of the switch for that person on the page when it enters a subpage etc. Currently, whenever I change the page it returns to the initial state.

What I've done so far: link

I did using HTML, CSS and JavaScript

    
asked by anonymous 06.08.2017 / 01:49

1 answer

1

Create a localStorage with values "1" for light background and "2" for dark background by adding the commented lines below 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 loads, the above script will check the value of localStorage and apply the change.

    
06.08.2017 / 03:25