1

need some help. I made a background picker for a page, so basically 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 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. Thank you in advantage.

Remedy Lane
  • 57
  • 1
  • 2
  • 5

3 Answers3

1

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);
donkeydown
  • 698
  • 7
  • 16
  • I ended up using this code snippet. It works in all the main and sub-pages. Also works in all browsers I tested. Thank you very much for the help! – Remedy Lane Nov 05 '13 at 17:47
0

Save the background variable in a cookie:

document.cookie = "bgimage=" + background;

then get the cookie:

$(function(){
   var bgCookie = getCookie("bgimage");
   $("html, body").css("background-image", bgCookie);
});

function getCookie(name) {
  var parts = document.cookie.split(name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie() method taken from: Get cookie by name

Community
  • 1
  • 1
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
  • This worked with the main pages, but when I added sub-pages (in sub-folders) it got screwed up. Also did not work in Opera at all. But thank you for the post. – Remedy Lane Nov 05 '13 at 17:46
0

you can add custom-background.js plugin to your website

https://github.com/CybrSys/custom-background.js

Shubham Badal
  • 1,125
  • 13
  • 33