Save div toggle state with jquery cookie

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I have an idea how to implement this, but it doesn't seem that of all the similar posts, anybody is able to give a simple example. I want to simply store the value of the toggle state of "marketing-message-global" in a cookie. If the user clicks "hide-marketing-message-btn", the toggled state will be stored in a cookie. When the user refreshes the page, the stored toggle state will be used, and hide the div that was toggled off.

<div id="marketing-message-global"> </div> <div id="hide-marketing-message-btn"> </div>  $(document).ready(function() {  if $('#hide-marketing-message-btn").clicked()  {     $("#marketing-message-global").hide();     $.cookie("toggle-state") == true;  }  if ($.cookie("toggle-state") == true) {     $("#marketing-message-global").hide(); } else if ($.cookie("toggle-state") == false) { $("#marketing-message-global").show(); }  }); </script> 

回答1:

I used jquery cookie plugin (https://github.com/carhartl/jquery-cookie)

    $(function(){        if($.cookie){            //By default, if no cookie, just display.            $("#marketing-message-global").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');     }      $('#hide-marketing-message-btn').on('click', function(){         $("#marketing-message-global").toggle();         //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", $("#marketing-message-global").is(':visible'), {expires: 1, path:'/'});  });  }); 


回答2:

I think this should work:

1) If you want to set the cookie by some events else:

$(document).ready(function() {     if ($("#hide-marketing-message-btn").prop("hidden") == "hidden")     {         $("#marketing-message-global").hide();         $.cookie("toggle-state") == true;     }     else     {         // ...      } }); 

2) Setting cookie by clicking on div and performing toggle at once:

$(document).ready(function() {     $("#hide-marketing-message-btn").click(function() {          if ($("#hide-marketing-message-btn").prop("hidden") == "hidden")         {             $("#marketing-message-global").hide();             $.cookie("toggle-state") == true;         }         else         {             // ...          }     }); }); 


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