0

I have two divs (staticclose and sads). The first one is visible and the other one is hidden. When I close the first div, the second one becomes visible and when I click the second div, the first one becomes visible. How can I use jquery.cookie to remember the state of the divs?

$('.staticclose').click(function(){ 
  $('.static-ad').toggleClass('hide');
  $('.sads').toggleClass('hide');
});

$('.sads').click(function(){ 
  $('.static-ad').toggleClass('hide');
  $('.sads').toggleClass('hide'); 
});
1
  • i have not heard of jquery cookie. but if you want to remember state, use html attributes Jul 8, 2015 at 2:11

2 Answers 2

0

Using jQuery.cookie as you ask in your question, you could do something like:

$('.staticclose').click(function(){ 
  $('.static-ad').toggleClass('hide');
  $('.sads').toggleClass('hide');
  $.cookie("last_state", "0", {path: "/"});
});

$('.sads').click(function(){ 
  $('.static-ad').toggleClass('hide');
  $('.sads').toggleClass('hide'); 
  $.cookie("last_state", "1", {path: "/"});
});
$(document).ready(function(){
  if ($.cookie("last_state") === "1") {
    //Do whatever you want
  } else {
    //Do whatever you want
  }
});
0

You can use cookies or HTML5 Storage. I prefer the second option.

https://github.com/carhartl/jquery-cookie

http://amplifyjs.com/api/store/

Simple example with amplify.

First store the object.

amplify.store( "yourObject", { foo: "bar" } );

Then retrieve it.

var retrievedValue = amplify.store( "yourObject" );

Simple example with jquery cookies.

Set:

$.cookie('staticclose', 'visible');
$.cookie('sads', 'invisible');

Get:

$.cookie('staticclose'); // "visible"
$.cookie('sads'); // "invisible"

Anyhow, you can use data attributes to accomplish this. But if your idea is remember the state after reloading the page, ok, go for the cookies idea.

Example with data attributes:

$("#div1").data("currentState", "visible");
$("#div2").data("currentState", "invisible");

To retrieve the data:

var div1 = $("#div1").data("currentState"); // It will be "visible"
var div2 = $("#div2").data("currentState"); // It will be "invisible"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.