Malekian Malekian - 4 months ago 55
HTML Question

save button background-color in localStorage

I'm trying now to switch the colors everytime user clicks on the button, and save background-color in localStorage. I've tried several options, but until now I didn't get it to work. Anyone a solution how to tackle this? thank u



<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Background Colour Changer</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

</head>
<body>


<script type="text/javascript">
if (localStorage.getItem('background') !== null) {
getColour = localStorage.background;
$('.btn-secondmenu').css('background', getColour);
}

$('.btn-secondmenu').click(function() {
if (getColour == 'blue') {
localStorage.removeItem('background');
$('.btn-secondmenu').css('background', 'red');
localStorage.setItem('background', 'red');
} else {
localStorage.removeItem('background');
$('.btn-secondmenu').css('background', 'blue');
localStorage.setItem('background', 'blue');
}
});
</script>
<button class="btn-secondmenu">Button</button>
</body>
</html>




Answer

JS Fiddle has problems with localStorage. Here is JS Bin.

The problem is, you weren't setting the variable getColour properly. You weren't actually updating it when the button is pressed.

Also, the button wasn't loaded when you were trying to set event listener to it. Wrap your code in $(document).ready() when using jQuery.

JS:

$(document).ready(function() {
  var getColour;
  if (localStorage.getItem('background') !== null) {
    getColour = localStorage.background;
    $('.btn-secondmenu').css('background-color', getColour);
  }

  $('.btn-secondmenu').on('click', function() {
    if (getColour == 'blue') {
      getColour = 'red';
      $('.btn-secondmenu').css('background-color', 'red');
      localStorage.setItem('background', 'red');
    } else {
      getColour = 'blue';
      $('.btn-secondmenu').css('background-color', 'blue');
      localStorage.setItem('background', 'blue');
    }
  });
});

HTML:

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<button class="btn-secondmenu">Button</button>