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