简体   繁体   中英

jQuery - Toggle element and save it with cookie

I am trying to use the jQuery Cookie plugin, and the jQuery toggle function:

Whenever someone toggle #launchpad, I want to get it's current state.

Example, if someone toggles it, and it becomes hidden, I then want to alert that it is now hidden - and vice versa.

This is my current code:

jQuery:

$(function(){
            if($.cookie){
                   //By default, if no cookie, just display.
                   $("#launchpad").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
            }

            $('#toggle-launchpad').on('click', function(){


                $("#launchpad").toggle(
                    if($(this).is(":visible")){
                        alert("visible!!");
                    }else{
                        alert("not visible");
                    }

                );
                //Save the value to the cookie for 1 day; and cookie domain is whole site, if ignore "path", it will save this cookie for current page only;
                $.cookie("toggle-state", $("#launchpad").is(':visible'), {expires: 1, path:'/'}); 
            });

        });

HTML:

 <div id="launchpad">
            <div id="toggle-launchpad" title="Toggle Launchpad" style="display: ;">
                <i class="fa fa-plus"></i>
            </div>
            </div>

I guess I cannot use an if function , inside the toggle function . Does anyone have a solution to my problem?

If you do:

$("#launchpad").toggle(400, function() {
    if($(this).is(":visible")){
        alert("visible!!");
    }else{
        alert("not visible");
    }
});

the code will be executed when the toggle function has complete. Note that the toggle function is async, so your $.cookie call will likely be called before the div is hidden/shown. Try:

$("#launchpad").toggle(400, function() {
    $.cookie("toggle-state", $("#launchpad").is(':visible'), {expires: 1, path:'/'});
});

Not that 400 is the (default) time the animation will take in ms. See the documentation .

Edit: Incase your comment is about the first part of your code, I would write it as:

if ($.cookie && $.cookie("toggle-state")) && $.cookie("toggle-state") === 'false') {
     $("#launchpad").hide();
}

This assumes that the div is visible by default (ie not hidden by CSS)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM