Sev
Sev

Reputation: 71

Jquery slideToggle & Cookies

im still fairly new to jquery and i got this slideToggle container, but now i want to save a cookie if the container is hidden or not so if one refreshes the page it keeps its current state.

I heard about the jquery cookie plugin but didn't really understand it to be honest. :(

Can anyone help me out?

My code so far is pretty simple:

$(function(){
 $("#hideslide").click(function(){
  $(this).next().slideToggle();
 });
});

Any help is highly appreciated

Upvotes: 0

Views: 1236

Answers (2)

Deep Frozen
Deep Frozen

Reputation: 2075

The jQuery Cookie plugin (found here) is the easiest way to use cookies with jQuery.

To set a cookie, this will do:

$.cookie("name", "content");

Getting a cookie is just as simple:

$.cookie("name");

So you should check on page load if the cookie is set:

if($.cookie("name") != null) {
    // Cookie set, action here
}

And on clicking the item to toggle, check if cookie is set. If it is set, remove it, else, set it:

if($.cookie("name") != null) {
    $.cookie("name", null); (null as value will remove the cookie)
}
else {
    $.cookie("name", "content");
}

I use this plugin myself and this is all you need. Easy.

Upvotes: 3

BLSully
BLSully

Reputation: 5929

If your client browser targets are IE8+, you could, and I think should, use localStorage for this.

localStorage.setItem('mySlideState', "open");

Then test:

if(localStorage.getItem('mySlideState') == 'open') {
    //do stuff
}

You would achieve this through the callback on slideToggle

$('#highSlide').slideToggle(function () {
    //set localStorage to value here
});

Mozilla docs: https://developer.mozilla.org/en/DOM/Storage

Upvotes: 0

Related Questions