Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery cookie.js to remember hide/show element?

I have found a great tutorial on how to show and hide a certain div on a page. I got the code working fine, but I would like to extend is to that the show/hide is remembered on page loads. I've looked for a solution jQuery cookie was the answer.. if I'd knew how to write the actual code that is.. Here's the current snippet:

<script type="text/javascript">
jQuery(document).ready(function() {
 // hides the group_desciption as soon as the DOM is ready
 // (a little sooner than page load)
  jQuery('#group_desciption').hide();
 // shows the group_desciption on clicking the noted link
  jQuery('a#slick-show').click(function() {
 jQuery('#group_desciption').show('slow');
 return false;
  });
 // hides the group_desciption on clicking the noted link
  jQuery('a#slick-hide').click(function() {
 jQuery('#group_desciption').hide('fast');
 return false;
  });
 // toggles the group_desciption on clicking the noted link
  jQuery('a#slick-toggle').click(function() {
 jQuery('#group_desciption').toggle(400);
 return false;
  });
});</script>

Any idea how I can add the cookies to remember the selection from the user? A code sample would be great since I'm still trying to grasp jQuery/Javascript in general :)

Thanks in advance :)

like image 339
Bowe Frankema Avatar asked Sep 13 '10 21:09

Bowe Frankema


1 Answers

Should be pretty easy. When you show the div add some code like:

jQuery.cookie('show_desc', 'yep');

...and when you hide the div:

jQuery.cookie('show_desc', 'nope');

...and then at the top of your code where you've got:

jQuery('#group_desciption').hide();

...change it to:

var shouldShow = jQuery.cookie('show_desc') == 'yep';
if( shouldShow ) { jQuery('#group_desciption').show(); }
else {             jQuery('#group_desciption').hide(); }

Or, alternatively:

jQuery('#group_desciption')[jQuery.cookie('show_desc') == 'yep' ? 'show' : 'hide']();

:)

like image 135
rfunduk Avatar answered Sep 22 '22 06:09

rfunduk