Set Cookie To Hide Div When Button Is Clicked
Solution 1:
There's a lot going on with your script.
Mark's got you on the right start: not quoting Accepted
is not going to make JavaScript happy; string literals have to have quotes.
Secondly, your jsFiddle doesn't link jQuery in. On the left side of the screen, under "Frameworks & Extensions", make sure you've chosen a version of jQuery.
Thirdly, jQuery doesn't have a built-in $.cookie
method; there are extensions that provide that, but it's not default jQuery. And if you were using a jQuery plugin, wouldn't you use that to set the cookie too? Instead you use native browser extensions to set the cookie.
Fourthly, because of the way jsFiddle works, you can't invoke JavaScript methods from within the HTML without some gymnastics. Much better to attach the appropriate functionality all within the JavaScript.
So, to get your cookie, you can do this:
var cookie = document.cookie.split(';')
.map(function(x){ return x.trim().split('='); })
.filter(function(x){ return x[0]==='TermsAndConditions'; })
.pop();
If the cookie exists, it will be a key/value array. Then you can check to make sure it exists and contains the value you're looking for:
if(cookie && cookie[1]==='Accepted') {
$("#terms-and-conditions").hide();
}
Then we'll move the click functionality out of the HTML and into the JavaScript:
$('.accept-button a').on('click', function(){
TermsAndConditions();
returnfalse;
});
Here's a working jsFiddle for you: http://jsfiddle.net/3d928/1/
Note that in your original example, you aren't hiding the #terms-and-conditions
element when the user clicks the link; all you're doing is setting the cookie. So it won't be hidden until the user re-loads the page. If you want to do both, simply hide the element in the click handler as well:
$('.accept-button a').on('click', function(){
TermsAndConditions(); // set cookie
$("#terms-and-conditions").hide(); // hide elementreturnfalse;
});
Solution 2:
Check this out : http://jsfiddle.net/bochzchan/fkFSZ/
functionTermsAndConditions(){
days=30;
myDate = newDate();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'TermsAndConditions=Accepted; expires=' + myDate.toGMTString();
}
functionCheckCookies(){
if ($.cookie("TermsAndConditions") === "Accepted")
{
$("#terms-and-conditions").hide();
}
}
Maybe you forget to include jquery cookie js
<scriptsrc="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script><divid="terms-and-conditions"><h1>Terms and Conditions</h1><p>Example Content</p><spanclass="accept-button"><ahref="#"onclick="TermsAndConditions()">Accept</a></span></div><ahref="#"onclick="CheckCookies()">Check</a>
Solution 3:
There are a couple things to consider:
- You should have quotes around
Accepted
in theif
statement. - You should use the
===
comparison, not!==
.
Post a Comment for "Set Cookie To Hide Div When Button Is Clicked"