Reputation: 51
I have a pop-up with a cookie that expires in one day (24 hours) and I would like that this cookie expires at midnight everyday (so the pop-up shows the first time you enter to the web every day). I'm not a programmer, so, please, could someone tell me what I have to change in my code? I have read some solutions to my question, but I don't know how to implement it.
//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
if ($.cookie("anewsletter") != 1) {
//centering with css
centerPopup();
//load popup
loadPopup();
}
//CLOSING POPUP
//Click the x event!
$("#popupContactClose").click(function(){
disablePopup();
$.cookie("anewsletter", "1", { expires: 1 });
});
//Click the bacground!
$("#backgroundPopup").click(function(){
disablePopup();
$.cookie("anewsletter", "1", { expires: 1 });
});
//Press Escape event!
$(document).keypress(function(e){
if(e.keyCode==27 && popupStatus==1){
disablePopup();
$.cookie("anewsletter", "1", { expires: 1 });
}
});
});
Thank you very much!
Upvotes: 5
Views: 5900
Reputation: 356
Ok - this will either create a cookie when a visitor first comes - that cookie will expire at 23:59:59 (the second before midnite), so if they visit from midnight or later, then it will redo the cookie. You could add your conditional code in the if visited == 0 section (where it sets the cookie) - this would only run if the cookie does not exists (or has expired).
var visited = 0;
function cookieTest() {
if (visited == 0) {
var exdate=new Date();
exdate.setHours(23);
exdate.setMinutes(59);
exdate.setSeconds(59);
document.cookie='visited=1; expires='+exdate+'; path=/';
}
else {
alert("you've been here before!");
}
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) visited = ( c.substring(nameEQ.length,c.length));
}
return null;
}
readCookie('visited');
cookieTest();
And jsFiddle.
Upvotes: 1
Reputation: 269
$.cookie
can take a date as expires
value, so you can use the following
var midnight = new Date();
midnight.setHours(23,59,59,0);
$.cookie('anewsletter', '1', { expires: midnight });
Upvotes: 10