Is it possible to cause the browser to cache a user action?

3

I've added a button on a website so the user can leave it in "night mode". But if he goes to a new story, the site will have night mode turned off.

Is it possible to have the browser cache this information, so that once it leaves the mode in night mode, the other news it accesses are already with this class?

var menu = document.querySelector('body.single-news');
var button = document.querySelector('button#skin-btn');
button.addEventListener('click', function() {
    var open = menu.classList.contains('light-skin');
    menu.classList.toggle('light-skin');
});

Removing the "light-skin" class activates the night mode.

    
asked by anonymous 20.02.2017 / 18:28

1 answer

6

There are several ways to implement this, only you can define which is the best or most suitable for your project.

My tip is to save this setting in localStorage

function ativarModoNoturno(){
    localStorage.setItem('modo_noturno_ativo', true);
}

Then whenever you open a page you check it

function modoNoturnoAtivo(){
    return localStorage.getItem('modo_noturno_ativo') || false;
}

Adapted code. Whereas the button switches from one mode to another, regardless of the current mode ( toggle , as you usually call it).

button.addEventListener('click', function() {
    // Pega o valor atual do localStorage
    var modoNoturnoAtivo = localStorage.getItem('modo_noturno_ativo') || false;
    // Salva o valor invertido no localStorage
    localStorage.setItem('modo_noturno_ativo', !modoNoturnoAtivo);

    // Código original
    var open = menu.classList.contains('light-skin');
    menu.classList.toggle('light-skin');
});

Obviously if you are working with a server-side technology to assemble the pages it will be much better to save a flag in the database and validate this before assembling the page.

    
20.02.2017 / 18:36