How to hide a div if cookie exists

2019-09-14 12:35发布

Looking to generate a cookie on a click of a button, then for it to check if the cookie exists, if the cookie exists then hide div.

Here is where I am at with my code, but I cannot seem to get the if statement to function as intended..

    (function ($) {
      
      $(".cookieSetter").click(function () {
         $.cookie('cookieMade', 'jobDone');
      });
      
      if ($.cookie('cookieMade', 'jobDone') == "true") {
        $('.box').hide();
      }
        
    })(jQuery);
    button {
      height: 48px;
      width: 112px;
      background: #fff;
      border: 2px solid #2d2d2d;
      color: #2d2d2d;
      font-size: 14px;
      font-weight: 600;
      text-transform: uppercase;
      cursor: pointer;
    }
    
    .blue {
      background: blue;
    }
    
    .box {
      width: 100px;
      height: 100px;
      margin-top: 10px;
    }
    <a class="cookieSetter" href="#"><button>Set cookie</button></a>
    <div class="blue box"></div>

3条回答
乱世女痞
2楼-- · 2019-09-14 12:55

Your usage of $.cookie('cookieMade', 'jobDone') is the setter of the cookie and not the getter. If you want to get the value of the cookie you should use $.cookie('cookieMade'), and check the returned value:

if ($.cookie('cookieMade') == 'jobDone') {
    // Do something if the cookie's value is 'jobDone'
}

In your case:

if ($.cookie('cookieMade') == 'jobDone') {
    // Do something if the cookie's value is 'jobDone'
    $('.box').hide();
}

update

The problem with codepen is that each time you reload the page you get a different path, and by default, $.cookie sets the path of the cookie to the current path.
You can set the path to / so the cookie will be valid for all of the pages in your domain:

$.cookie('cookieMade', 'jobDone', {path: '/'});

This will work in codepen (and should also work in your website).

查看更多
贼婆χ
3楼-- · 2019-09-14 13:04

Your syntax for checking the cookie isn't correct. You need to use the 'getter' for the value. Also note that you can use toggle() to show/hide the element as needed. Try this:

(function($) {
    $(".cookieSetter").click(function () {
        $.cookie('cookieMade', 'jobDone');
    });

    $('.box').toggle($.cookie('cookieMade') != 'jobDone');
})(jQuery);
查看更多
Root(大扎)
4楼-- · 2019-09-14 13:19
When you set the cookie you can raise event and subscribe that event wherever is
needed.
(function ($) {  
  $(".cookieSetter").click(function () {
     $.cookie('cookieMade', 'jobDone');
    $(document).triggerHandler('_cookieSetter', true);
  });  
  $(document).off('_cookieSetter.add').on('_cookieSetter.add', function () {
               if ($.cookie('cookieMade') == 'jobDone') {
    $('.box').hide();
}});
})(jQuery);
查看更多
登录 后发表回答