Search code examples
jquerycookiestoggletoggleclass

Simplest way to add cookies to jQuery toogle


This is my first post on stackoverflow :) I spent whole night to try many ways to do the same thing, but I'm a beginner so I give up and ask for help.

Question was answered many times but I can't find just simple way to make TOGGLE remember current state. I don't want to start my work with jQuery with bloated code.

I need to create just dead simple open/close panel and I found toggle() or toggleClass() will give me what I'm want.

Final working code from Miro shortened and fixed by me is:

$(document).ready(function () {
    $('p').toggleClass('red', $.cookie('currentToggle') === 'on');
    $('button').toggleClass('yellow', $.cookie('currentToggle') === 'on');
});

$("button").click(function () {
    $("p").toggleClass("red");
    $(this).toggleClass("yellow");
    $.cookie('currentToggle', $("p").hasClass('red') ? 'on' : 'off');
});

Thanks Miro!


Solution

  • try something like this:

    $(document).ready(function () {    
        $('p').toggleClass('red', $.cookie('currentToggle') === 'on');  
    });
    $(function(){
    
        $("button").click(function () {
            $("p").toggleClass("red");
            $(this).toggleClass("yellow");      
            $.cookie('currentToggle', $("p").hasClass('red')?'on':'off' );
        });
    });