Search code examples
jquerycookiesstylesheet

jQuery Cookie not being read


I was wondering if you were able to help me at all. I am trying to read a cookie in jQuery with regards to a style switcher but it just isn't playing fair at all. I have had a look around on Google and also on the jquery cookie plugin website to no avail

I am using the jquery.cookie plugin.

I can set the cookie just fine, but reading it is another matter altogether.

I am setting the cookie to be the last stylesheet used and when I reload the page I am wanting that value to be used as the stylesheet that is loaded.

I am using the function as follows to read the cookie:

$(document).ready((function() {
            if($.cookie("css")) {
                $('style[id="colours"]').text('@import url("css/' + $.cookie("css") + '.css');
            });
        });

However, when I use this the rest of the jQuery breaks. I have tried it using just $function() and I have put an if else in there and it just isn't working.

If I take it out, the page and jquery loads just fine.

As I say, the cookie sets fine. I have tested it with an alert and also in firebug and on change the cookie changes.

This is what I have used to set the cookie:

$(document).ready(function() {
            $('#green').click(function() {
                $('style[id="colours"]').text('@import url("css/green.css");')
                $.cookie("css",$(this).attr('id'), {expires: 30, path: '/'});
            });
        });

You can view what I have so far here: http://www.chriswilcox.me.uk/test/cv and see what I mean. I have commented out the reading of the cookie as it breaks everything else.

I would totally appreciate any help you guys and gals have to offer.


Solution

  • Your code has an extra )

    $(document).ready(function () { // also here you had an extra (
        if ($.cookie("css")) {
            $('style[id="colours"]').text('@import url("css/' + $.cookie("css") + '.css);');
             // you are missing another one up there at @import
        } // here you don't need to close )
    });