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

浪子不回头ぞ 提交于 2019-12-06 03:27:38

问题


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 :)


回答1:


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']();

:)



来源:https://stackoverflow.com/questions/3704452/using-jquery-cookie-js-to-remember-hide-show-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!