tags:

views:

31

answers:

3

I want to set a cookie when a person clicks on a link, then i want to get that cookie and have it somehow add the class 'pinned' to '#navigation'. I'm not too sure if this is right, i'm using the jquery cookie plugin, ugh. this is the code I have so far:

to set the cookie:

$.cookie('CookieName':'#navigation');

gets the cookie, adds the class 'pinned' onto the element #navigation

 $("#" + $.cookie('cookieName')).addClass("pinned");

But whenever i put this code anywhere in my JS file, it causes all of the JS not to work anymore, so it breaks my whole page.

+2  A: 

You can store a value in a cookie, but you can't attribute a class (or id) to one (although obviously you can name a cookie, but it's not quite the same thing). You could, instead, do something like this:

$.cookie('class','pinned',{expires:30});

and then retrieve the value:

var pinnedClass = $.cookie('class');

$('#navigation').addClass(pinnedClass);
David Thomas
all the JS on my page works now with your code, but its not adding the class, i did `alert(pinnedClass)` and it gave me [object Object], any ideas?
android.nick
oh wow the problem is with chrome, because I open the exact same page in FireFox 4 and it works just fine. hmmm, thanks man, weirrrd. and yes I DO have chrome set to allow local cookies.
android.nick
is it correct that the best way to remove a cookie is: $.cookie('class', null);
android.nick
@android.nick, yeah that seems to be the preferred way. Certainly it's the one endorsed by the plug-in itself.
David Thomas
+2  A: 

You have a syntax error while setting the cookie, and you're also retrieving the cookie with the wrong spelling:

$.cookie('CookieName', 'navigation');

$("#" + $.cookie('CookieName')).addClass("pinned");
Jacob Relkin
A: 

you can use normal javacsript code to get the cookie like below.. the following code should work

this.getCookie = function(name) {
    if (document.cookie.length > 0) {
        start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            start = start + name.length + 1;
            end = document.cookie.indexOf(";", start);
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(start, end));
        }
    }
    return "";
gov