Search code examples
javascriptjquerycookiessetcookie

Toggle cookies & classes when a button is pressed


I'm trying to figure out a way in order to toggle cookies + classes when a button is pressed.

If: button with a class name of btn_fixed is pressed it:
- sets cookie "fixed" to "true",
- adds class to the "<header>" called "fixed", also when the page is loaded any other time the class "fixed" is applied, as the cookie is set to true.
Else:
- sets cookie "fixed" to "false" (default value, when entering the site for the first time),
- removes class "fixed" from the "<header>"

This is what I got so far, which I can now see is very far from what I want it to do:

if (jQuery.cookie("fixed") != "true") {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').addClass('fixed');  
            jQuery.cookie("fixed", "true");  
        });  
    }  
    else  
    {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').removeClass('fixed');  
    jQuery.cookie("fixed", "false");
    }  



<a href="#" class="fixed_btn">Fixed/Fluid</a>  
<header>aaa</header>​

http://jsfiddle.net/UWLdq/7/

Thanks for your help.


Solution

  • You need to just toggle the class initially, then bind a click event that does it.

    jQuery(document).ready(function($) {
        // set class initially based on current cookie value
        $('.cookiefixed').toggleClass('fixed', $.cookie("fixed") == "true");
        // on click, toggle both class and cookie value
        $('a.fixed_btn').click(function() {
            $('.cookiefixed').toggleClass('fixed');
            $.cookie("fixed", $('.cookiefixed').hasClass('fixed'));
        });
    });​
    

    I suggest not using 'header' as a selector though due to the fact that there can be more than one header on a page, and i doubt you'd want them all to get this class.

    Demo: http://jsfiddle.net/UWLdq/6/