john
john

Reputation: 409

change background image and set cookie

Trying to change the body background pattern to corresponding thumbnail clicked then save with cookie, switches fine but it doesn't save the cookie when I refresh the page.

Is this the right way to do it?

Can anyone help please?

<script type="text/javascript">
     function changeBg(bgImage) {
                $("body").css({"background-image": bgImage});
                $.cookie("bgimg", bgImage, { expires: 7});
            }


            $('.bgswitch.pat1').click(function()
            {   
                changeBg("url(/images/patterns/p1.png)");
            });

            $('.bgswitch.pat2').click(function()
            {
                changeBg("url(/images/patterns/p2.png)"); 
            });
            $('.bgswitch.pat3').click(function()
            {
                changeBg("url(/images/patterns/p3.png)"); 
            });
            $('.bgswitch.pat4').click(function()
            {
                changeBg("url(/images/patterns/p3.png)"); 
            });
            $('.bgswitch.pat5').click(function()
            {
                changeBg("url(/images/patterns/p4.png)"); 
            });
            $('.bgswitch.pat5').click(function()
            {
                changeBg("url(/images/patterns/p5.png)"); 
            });
            $('.bgswitch.pat6').click(function()
            {
                changeBg("url(/images/patterns/p6.png)"); 
            });
            $('.bgswitch.pat7').click(function()
            {
                changeBg("url(/images/patterns/p7.png)"); 
            });
            $('.bgswitch.pat8').click(function()
            {
                changeBg("url(/images/patterns/p8.png)"); 
            });
            $('.bgswitch.pat9').click(function()
            {
                changeBg("url(/images/patterns/p9.png)"); 
            });
            $('.bgswitch.pat10').click(function()
            {
                changeBg("url(/images/patterns/p10.png)"); 
            });
</script>

Upvotes: 0

Views: 1417

Answers (1)

Sark
Sark

Reputation: 4546

Use jquery ready event to set the background pattern at page refresh, like this

$(document).ready(function(){
   $("body").css({ "background-image": $.cookie("bgimg") });
});

also you can assign css class like "thumb" for all thumbnail images and optimise your code like

$(document).ready(function(){

   /* for page refresh */
   $("body").css({ "background-image": $.cookie("bgimg") });

   /* for thumbnail click event */
   $(".thumb").click(function(){
      $("body").css({"background-image": $(this).attr('src')});
      $.cookie("bgimg", "url("+ $(this).attr('src') +")", { expires: 7});
   });

});

That's all you need.

Upvotes: 1

Related Questions