How to save color of background using javascript localstorage?

Viewed 24

I need a function that changes background color on click and saves it. How can do that using localStorage?

My code:

const colors = document.querySelectorAll('.color-btn');
colors[0].addEventListener('click', () => {
    document.body.style.backgroundColor = 'red'
})

Now how can I make that when I reload the page the function doesn't reset (no jquery).

2 Answers

You can just try this:

const colors = document.querySelectorAll('.color-btn');
      colors[0].addEventListener('click', () => {
        document.body.style.backgroundColor = 'green'
        localStorage.setItem('color', 'green');
      });

      window.onload = () => {
        const color = localStorage.getItem('color');
        document.body.style.backgroundColor = color;
      }

As below

const colors = document.querySelectorAll('.color-btn');
colors[0].addEventListener('click', () => {
    const COLOR = 'red';
    document.body.style.backgroundColor = COLOR;
    localStorage.setItem('background-color', COLOR);
})

Related