Is it possible to make the browser flag a user action?

Asked

Viewed 73 times

3

I added a button on a website so that the user can leave it in "night mode". But if it goes to new news, the site will be deactivated at night mode.

It is possible to have the browser cache this information, so that once it leaves the mode in night mode, the other news that it accesses are also 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 night mode.

  • 3

    Curl is one of the most beautiful verbs we brought to English.

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 to localStorage

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

There 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 the other, regardless of the current mode (toggle, as they say).

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 one flag in the database and validate this before mounting the page.

  • As I edited the post, would I add this function inside the other? Or would I put some "if’s" to check if there is a "light-skin" class in the body?

  • @Andrébisewski I updated the code.

Browser other questions tagged

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