Search code examples
javascripthtmlcsscookiesbackground-image

Keep user selected background throughout all the pages on the site


I made a background picker for a page. There are 4 different background-images that users can select from.

Here is my code and script I used for this:

HTML:

<ul>
  <li id="color-1"></li>
  <li id="color-2"></li>
  <li id="color-3"></li>
  <li id="color-4"></li>
</ul>

SCRIPT:

<script>
    $('ul li').click(function() {
    var background = $(this).css('background-image');
    $("html, body").css("background-image", background);
});
</script>

The issue is that when I switch page the background image resets to the default one. I know this could be handled by setting cookies. I tried several methods, but none worked.

Can someone please help me out with this one?


Solution

  • When selected, store the background in the localStorage

    <script>
        $('ul li').click(function() {
        var background = $(this).css('background-image');
        $("html, body").css("background-image", background);
        localStorage.background = background;
    });
    </script>
    

    When loading a page, apply it.

    $("html, body").css("background-image", localStorage.background);