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

233
Visualizações
How to change site colors and save in Local Storage?

How can I change site colors & save in localStorage?

I have a function in jQuery to allow users to the change background color of my website. The problem is, if they refresh the page background color automatically goes back to the default. How can I use localStorage with this jQuery function?

$(document).ready(function() {
  /*-- Change color bg WPEAR.COM --*/
  var resultPlaceholder = $('body');
  var greenAndWhite = $('#green-and-white');
  var redAndYellow = $('#red-and-yellow');
  var blueAndPink = $('#blue-and-pink');
  var yellowAndPink = $('#yellow-And-Pink');

  greenAndWhite.click(function() {
    resultPlaceholder.css({
      'background': 'green'
    });
  });
  
  redAndYellow.click(function() {
    resultPlaceholder.css({
      'background': 'red'
    });
  });
  
  blueAndPink.click(function() {
    resultPlaceholder.css({
      'background': 'blue)'
    });
  });
  
  yellowAndPink.click(function() {
    resultPlaceholder.css({
      'background': 'yellow'
    });
  });
})
/* -- change color wpear.com -- */

.button-wrapper {
  position: fixed;
  left: 0;
  display: grid;
  top: 40%;
  margin: 0;
}

.change-color {
  width: 40px;
  height: 40px;
  cursor: pointer;
  border: none;
}

#red-and-yellow {
  background: red;
}

#green-and-white {
  background: green;
}

#blue-and-pink {
  background: blue;
}

#yellow-And-Pink {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class='button-wrapper'>
  <button class='change-color' id='green-and-white' />
  <button class='change-color' id='red-and-yellow' />
  <button class='change-color' id='blue-and-pink' />
  <button class='change-color' id='yellow-And-Pink' />
</div>

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

  1. Write a function to save the selected theme to localStorage:
function saveTheme(color) {
   localStorage.setItem('theme', color)
}
  1. Save theme on every change:
greenAndWhite.click(function(){
   resultPlaceholder.css({'background':'var(--linear-graBO)'});
   saveTheme('var(--linear-graBO)')
});
// do this for each change
  1. When page loads - check localStorage for saved theme [put in the <head> so it should run immediately]:
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
   document.body.style.background = savedTheme
}
about 4 years ago · Santiago Gelvez Relatório

0

To go what you require simply set the localStorage value in the click handler. Then read it back out and set it when the page next loads:

Also note that your JS code can be DRY'd up by using the same event handler for all button elements and setting the background to match the clicked button.

jQuery($ => {
  let $body = $('body');
  let defaultBgColor = localStorage.getItem('body-bg-color');
  defaultBgColor && $body.css('background-color', defaultBgColor);

  $('.change-color').on('click', e => {
    let bgColor = $(e.target).css('background-color');
    $body.css('background-color', bgColor);
    localStorage.setItem('body-bg-color', bgColor);
  });
});

Finally, note the use of background-color, not background. The latter is a shortcut and using it to set the background color only may override other background-related styling.

Here's a working jsFiddle example, as SO snippets are sandboxed and don't allow access to localStorage.

about 4 years ago · Santiago Gelvez 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