Change the color of a button and keep it changed after the user leaves and returns

0
Is there any way to make a page keep the color change of a button (or link) with a function such as the CSS "a: visited" but that change should remain even after the user exits the site and return later?

    
asked by anonymous 23.12.2017 / 19:33

1 answer

0

Since what you want to do does not involve security issues, you just want to change the style of a button, you can use #

The localStorage stores information in the browser in a variable that can be retrieved at any time, and this information does not go out when the site exits or when the browser is closed.

Defining a localStorage

You can create directly using the syntax:

localStorage.botao = "algum_valor";

Where botao is the name given to localStorage and algum_valor is its value. You can put a specific value that can be used later or simply set true , just to indicate that it exists:

localStorage.botao = true;
  

Remember that putting localStorage.botao = false; will not serve   for Boolean checking, that is, localStorage.botao = true; e    localStorage.botao = false; will return true in    if(localStorage.botao) . That's because no is checking its value,   but rather if it exists.

Returning to reasoning ...

Assuming you have 2 class in your CSS, one for each button color:

.botao_vermelho{
    background: red;
}

.botao_verde{
    background: green;
}

When changing the color of the red button to green and you want the user to always have the green button when returning to the site, the localStorage.botao = true; and enter in your code the verification below:

$(document).ready(function(){
    var button = $("#id_do_botao"); // pego o botão pelo id
    if(localStorage.botao){ // verifico se o localStorage "botao" existe

        // removo a class vermelho e adiciono a verde
        button.addClass("botao_verde")
        .removeClass("botao_vermelho");
    }
});

Removing localStorage

Once created, localStorage has no deadline to expire. It will only be deleted via option in the browser, if it is uninstalled or by the statement below:

localStorage.removeItem("botao");

So when you no longer need it, insert the line above into the part of your code where you want to do it.

    
24.12.2017 / 00:00