My first post, newbie here and to jQuery… I’m reading, studying, trying to get a solid background understanding of jQuery, but I can’t help being impatient and jumping in trying to do stuff!
This bit of code has me baffled. It’s a sequential toggle background switcher with cookie that I’ve spent days putting together and trying to make work. What works: it switches between the four backgrounds sequentially, and it appears to set a cookie each time, because the alert confirms it. What doesn’t work: the background selection doesn’t “stick”. When I refresh the page, the background returns to the default as set by the css. I know there’s some small but crucial thing wrong, and I’ve spent many hours trying to figure it out by looking at other examples, here on SO and elsewhere. But no other examples I’ve found use a toggle sequentially like this. So, looking for a little help, and thanks in advance!
I’m using jquery-1.7.2 and the jquery.cookie plugin.
<script type="text/javascript">
$(document).ready(function() {
var bgSwitch = $.cookie("oink");
if (bgSwitch) {
$("body").css("background-image", bgSwitch);
}
});
alert( $.cookie("oink") );
$("#switcher").toggle(
function () {
$("body").css({"background-image": "url(images/background/hashbones.gif)"});
$.cookie("oink", "hashbones!", { expires: 7});
},
function () {
$("body").css({"background-image": "url(images/background/pattern-tile-3.gif)"});
$.cookie("oink", "tiles!", { expires: 7});
},
function () {
$("body").css({"background-image": "url(images/background/dots.gif)"});
$.cookie("oink", "DOTS!!!!", { expires: 7});
},
function () {
$("body").css({"background-image": "url(images/background/lines-diag-8px.gif)"});
$.cookie("oink", "lines again!", { expires: 7});
}
);
</script>
<style>
body { background: #fff url(images/background/lines-diag-8px.gif) repeat; }
</style>
When you toggle the switcher you create a cookie set its value with one possible value (hashbones! / tiles! / DOTS!!!! / lines again!). Assume the current value is “tiles!”.
When the page is refreshed bgSwitch get the value of the cookie – “tiles!”. So actually you do:
Which makes nothing.
Change the possible values of the cookie to the images themselfs. Something like:
Hope this helps!