Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
How to remember the buttons click state and their functions with local storage?

I have many buttons that change/add/remove elements. Some of the elements are dynamic e.g. clicking button one will create button two etc.

I'd like to save the state of the buttons/page in local storage. If I clicked button one, and then two, the background is now red. When the visitor returns (after browser close) it will be as if they have already clicked one>two and will see the red background as before.

I've been reading Mozilla setItem and every post on Stackoverflow about local storage but I can't find any examples of this exact scenario. https://jsfiddle.net/oh9q2Lzw/1/

$('.one').on('click', function() {
  $('.blue').removeClass('blue').addClass('green');
});

$('.two').on('click', function() {
  $('.green').removeClass('green').addClass('red');
});
button {
  padding: 10px 40px;
}

.blue {
  width: 200px;
  padding: 20px;
  background: blue
}

.green {
  width: 200px;
  padding: 20px;
  background: green
}

.red {
  width: 200px;
  padding: 20px;
  background: red
}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<br>
<div class="box">
  <button class="one">one</button>
  <button class="one">one</button>
  <button class="two">two</button>
</div>
<br>
<div class="blue"></div>
<br>
<div class="blue"></div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your example, the only memory the page needs is the class name of the divs applied when the style was last changed.

Therefore, the simple solution is to store the class name in local storage each time it changes by modifying your button events as follows:

    $('.one').on('click', function() {
      $('.blue').removeClass('blue').addClass('green');
      localStorage.setItem("div-class", "green");
    });

    $('.two').on('click', function() {
      $('.green').removeClass('green').addClass('red');
      localStorage.setItem("div-class", "red");
    });

When the page loads, the hard-coded class is always "blue" and so this can be changed if a value is stored in local storage.

This is done by adding a function to the window.onload event:

window.onload = function() {
      if (localStorage.getItem("div-class")) {
            $('.blue').removeClass('blue').addClass(localStorage.getItem("div-class"));
      }
    };

The SO snippet tool doesn't allow local storage access but I've modified your JS fiddle with a working example: https://jsfiddle.net/g5wqjo2h/

I've also made a modified version with an extra button to allow you to clear localStorage during development. If the clear memory button is clicked, when the js Fiddle is next run or loaded, the divs return to the default blue class. Otherwise, the previous colour is loaded from localStorage. : https://jsfiddle.net/g5wqjo2h/1/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda