Keep the last change in input saved in the browser

Asked

Viewed 37 times

1

When you click the button it changes the background of the BODY tag, I need that when reload the page it keeps the color that was selected before, I think with localstorage work but I don’t understand much of it.

function mudarNome3(){   
 var element = document.body;  element.classList.toggle("dark-mode");
 
 if(document.getElementById("buttonmodoclaro").value == "MODO CLARO")
 {
  document.getElementById("buttonmodoclaro").value = "MODO ESCURO";
 } 
 else
 {
  document.getElementById("buttonmodoclaro").value = "MODO CLARO";
 }
}
.dark-mode {
  background-color: black;
  color: white;
}

.dark-mode #buttonmodoclaro {
    color: white;
    font-weight: bold;
    border: 1px solid #a0a0a0;
    box-shadow: 0 0 4px 0 #8e8e8e inset;
}

#buttonmodoclaro{
    
    padding: 6px;
    border: 1px solid #561010;
    border-radius: 6px;
    margin-left: 21px;
    cursor: pointer;
    box-shadow: 0 0 6px 0 #171717 inset;
    color: red;
    background: none;
    font-variant: all-small-caps;
    font-family: sans-serif;
    font-size: 14px;
}
<input type='button' id='buttonmodoclaro' onclick='mudarNome3();' value='MODO CLARO'>

1 answer

2


The localStorage can really suit you, you would need to save the current value in it, ie whenever the button is clicked and recover as soon as the page is loaded.


Your JS would look more or less like this:

function restauraSalvo() {
  //Recupero o valor salvo no localStorage
  let valorSalvo = localStorage.getItem("dark-mode");

  //Se existir valor e for diferente do atual, troco...
  if (valorSalvo && valorSalvo !== document.getElementById("buttonmodoclaro").value)
  {
    mudarNome3();
  }
}

function mudarNome3(){   
  var element = document.body;

  element.classList.toggle("dark-mode");

  const botaoModo = document.getElementById("buttonmodoclaro");

  if(botaoModo.value == "MODO CLARO")
  {
    botaoModo.value = "MODO ESCURO";
  } 
  else
  {
    botaoModo.value = "MODO CLARO";
  }

  //Após efetuar a troca, salvo no localStorage
  localStorage.setItem("dark-mode", botaoModo.value);
}

restauraSalvo();

The function restauraSalvo is invoked as soon as the page is loaded and brings the value saved in localStorage and updates to the same if necessary.

Already the function mudarNome3 saves the current value in localStorage is always triggered.

See online: https://repl.it/repls/PresentLustrousDesigner

Note: The localStorage does not work on stacksnippets, so I put the example on another page.


Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

  • It was the way I wanted it, 100%, thank you!

Browser other questions tagged

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