-1

I have this toggleClass function:

$(document).ready(function() {  
    $("button#playersize").click(function(){
        $("#wrapper").toggleClass("small large");
        $(".divone").toggleClass("small large");
        $(".divtwo").toggleClass("small large");
    });
});

This changes the classes of the divs between "small" and "large" onclick button.

I would like to save the class of the divs (#wrapper, .divone, .divtwo) to a cookie. And on reload, the class should be the saved one.

How do I manage this?

I have the jquery cookie plugin embedded already. My code is probably a bit redundant, sorry.

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
dee
  • 25
  • 5

1 Answers1

1

Here is what you can try:

$(document).ready(function() {
    // replace the classes from the cookies
    // example if you want to check the cookie first
    if ($.cookie('class_wrapper').length > 0) {
        $("#wrapper").attr('class', $.cookie('class_wrapper'));
    } else {
        $("#wrapper").attr('class', 'small');
    }
    $(".divone").attr('class', $.cookie('class_divone'));
    $(".divtwo").attr('class', $.cookie('class_divtwo'));
    // bind the click event 
    $("button#playersize").click(function(){
        $("#wrapper").toggleClass("small large");
        $(".divone").toggleClass("small large");
        $(".divtwo").toggleClass("small large");
        // replace the cookie values
        $.cookie('class_wrapper', $("#wrapper").attr('class'));
        $.cookie('class_divone', $(".divone").attr('class'));
        $.cookie('class_divtwo', $(".divtwo").attr('class'));  
    });
});

Caveat: not tested yet

JMax
  • 26,109
  • 12
  • 69
  • 88
  • Thank you very much! What if the divs need the class "small" by default, when nothing is saved in the cookie? The class should only be small OR large. – dee Nov 16 '11 at 11:37
  • I've edited my answer to show an example you can adapt for the other cases. Yet, you should probably define the default behavior in your HTML generation (PHP, ASP or else) – JMax Nov 16 '11 at 12:52
  • it looks pretty good, but gives me the error: "Uncaught ReferenceError: len is not defined" do you know where the problem is? – dee Nov 16 '11 at 17:44
  • sorry, I'm mixing up languages, you have to use `.length`. I edited my code – JMax Nov 16 '11 at 19:05
  • thank you so far, seem to work in chrome and firefox, but in safari and IE it looks like there is a conflict with other jQuery stuff. My jquery-ui sortable for example is no more working. Any idea? – dee Nov 16 '11 at 21:30
  • we can't help you more without seeing more code. Have a look at some debug to see if the console raise any error. If it still doesn't work, you'd better ask a new question giving as much information as you can. – JMax Nov 17 '11 at 07:16
  • Firebug gives me: "$.cookie("class_wrapper") is null" as a error. – dee Nov 23 '11 at 09:14