views:

280

answers:

3

Hi,

It's my first time dealing with cookies in JavaScript and the below script works fine on my local PC but when I upload it here: example it fails.

$(document).ready(function(){

        // Get Cookie 
        var getCookie = document.cookie;

        if(getCookie == "stylesheet=blue")
        {
              $("[rel=stylesheet]").attr({href : "blue.css"});
        }
        else if(getCookie == "stylesheet=main")
        {
           $("[rel=stylesheet]").attr({href : "main.css"});
        }

     // Set Stylsheet back to Main
     $('#reset').click(function()
     {
              $("[rel=stylesheet]").attr({href : "main.css"});

        var setCookie = document.cookie = "stylesheet=main";
     });   

        // Set Stylsheet Blue
        $('#blue').click(function()
     {
       $("[rel=stylesheet]").attr({href : "blue.css"});

       var setCookie = document.cookie = "stylesheet=blue";
     });
  });

Any ideas?

A: 

Have you tried adding an expiration date to the cookie so that it hard sets it?

document.cookie = "stylesheet=blue; expires=Thu, 5 May 2011 20:47:11 UTC; path=/"

This is a hard coded example, but you can set the datetime as needed.

AaronS
thanks for the reply, unfortunately it's still the same
Keith Donegan
+1  A: 

The problem is, you are using google analytics, which also sets its own cookies. So, when reading document.cookie property, it will never have the value eg. "stylesheet=blue", because it will contain information on other cookies. Call

alert(document.cookie);

and check the value for yourself.

You should use a function for getting cookie value, for example

function getCookie(N){
   if(N=(new RegExp(';\\s*'+N+'=([^;]*)')).exec(';'+document.cookie+';'))
      return N[1]
}

or use jQuery cookie plugin

Rafael
Lovely stuff! cheers mate
Keith Donegan
I'm glad I could help
Rafael
+1  A: 

When you get the cookie back, it isn't just the string "stylesheet=blue" but has other information in it as well.

For me the string I get back looks like this:

"stylesheet=blue; __utma=168444603.22445052401845424.1242318397.1242318397.1242318397.1; __utmb=168444603.5.10.1242318397; __utmc=168444603; __utmz=168444603.1242318397.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/864324/cookie-sets-on-localhost-but-not-on-live-server"

check that the string contains "stylesheet=blue" instead of checking equivalance.

Edit: See what @Rafael said. I like the JQuery cookie plugin

Geoff