Sterling King
Sterling King

Reputation: 163

How to save color of background using javascript?

I'm attempting to allow a web visitor to change the color of a page's background and make sure that when they refresh the page, their background color preference is still displayed on the page.

I've tried using localStorage.setItem() but it doesn't seem to be working. Any suggestions?

HTML

<button id="changeColorButton" class="btn-secondmenu">Button</button>
<select name="colors" id="changeColorSelect">
   <option value="red">Red</option>
   <option value="green" selected="selected">Green</option>
   <option value="yellow">Yellow</option>
   <option value="black">Black</option>
</select>

JS

$('#changeColorButton').click(function() {
    var color = $('#changeColorSelect').val();
    console.log(color)
    $('body').css("background-color",color);
    localStorage.setItem('background', $(this).val());
});

Any help is appreciated, thanks!

Upvotes: 1

Views: 1215

Answers (2)

Aakash
Aakash

Reputation: 1515

In your code, you are using the click event listener function

$('#changeColorButton').click(function() {...}

In you click event listener this refers to the button and not the changeColorSelect select. So that is why local storage is not able to store your color.

Instead this would work

$('#changeColorButton').click(function() {
    var color = $('#changeColorSelect').val();
    console.log(color)
    $('body').css("background-color",color);
    localStorage.setItem('background', color);
});

Hope it helps!

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

This line

localStorage.setItem('background', $(this).val());

will save the value of button element $('#changeColorButton'), if there is any

Instead make it

localStorage.setItem('background', color);

Upvotes: 4

Related Questions