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

508
Visualizações
How to store changes in background color using localStorage in JavaScript?

I have several html elements such as body, div, and nav whose background color can be changed by the user globally.

These elements are targeted using a specific class name.

The way it works is: There are 3 buttons to change the bg.color of each of the 3 elements. When a user clicks on a button, it will open a modal containing all the colors available, in which there are at least 300 different colors. Once they click on a hex value, all the elements with that specific class name will change its color.

Please see this example below. I removed the modal for simplicity and only targets 1 class name: card-bg.

function changeBgColor(color){
    var elements = document.getElementsByClassName("card-bg")
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.background=color;
    }
}
<div class="card-bg">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit reiciendis asperiores incidunt accusamus mollitia eligendi culpa ea iure harum, repellendus animi natus odio unde explicabo, perspiciatis consectetur laudantium eius. Nisi!
</div>

<br/>

<div class="card-bg">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit reiciendis asperiores incidunt accusamus mollitia eligendi culpa ea iure harum, repellendus animi natus odio unde explicabo, perspiciatis consectetur laudantium eius. Nisi!
</div>

<div style="background-color: #ffebee" class="text-dark">
    <p>Red 50 <span><a onclick="changeBgColor('#FFEBEE');">#FFEBEE</a></span></p>
</div>
<div style="background-color: #ffcdd2" class="text-dark">
    <p>100 <span><a onclick="changeBgColor('#FFCDD2');">#FFCDD2</a></span></p>
</div>
<div style="background-color: #ef9a9a" class="text-dark">
    <p>200 <span><a onclick="changeBgColor('#EF9A9A');">#EF9A9A</a></span></p>
</div>

This is working fine, but I would like to add something more to improve its function which is the localStorage. So that when users shut down their computers, they will be able to save their customization.

Additionally, I would like to have a new button to reset these colors to default if the user chooses to.

I've just learned about it and I'm still trying to figure out JavaScript in general... though I'd like to implement this feature.

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

0

In your change color function, if a color is provided, set it to local storage. If it isn't provided, retrieve the value saved to the local storage. Then change the color of the elements.

function changeBgColor(color){
    // if provided color, set color to LS
    if (color) window.localStorage.setItem('bgColor', color);
    // if no provided color, check LS for color, and if no color in LS, fail silently
    else if (!(color = window.localStorage.getItem('bgColor'))) return;

    // update the page
    var elements = document.getElementsByClassName("card-bg")
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.background=color;
    }
}

and in your load function, just update the page by calling the same function with empty args:

window.addEventListener('DOMContentLoaded', () => changeBgColor());
about 4 years ago · Juan Pablo Isaza Relatório

0

You can create a variable holding the color and store it in localStorage whenever convenient, instead of storing it in localStorage when you set it, as well:

var bgcolor = "#000000"
function changeBgColor(color) {
    bgcolor = color; // Whenever the color is changed, it's stored in bgcolor
                        so that you can quickly set localStorage to it.
    var elements = document.getElementsByClassName("card-bg")
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.background = color;
    }
}

function storeCurrentColor() { // Stores the current background color (which was stored in bgcolor) in localStorage
    window.localStorage.setItem("bgcolor", bgcolor);
}

function getCurrentColor() { // Gets the current background color and moves from localStorage into bgcolor.
    bgcolor = window.localStorage.getItem("bgcolor");
}
function getAndSetCurrentColor() { // Gets the color from localStorage and sets the background color to it.
    getCurrentColor();
    changeBgColor(bgcolor);
}

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