Skip to content Skip to sidebar Skip to footer

How To Hide A Div If Cookie Exists

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

Solution 1:

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

Solution 2:

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

Post a Comment for "How To Hide A Div If Cookie Exists"