March 15, 2017

Make a one time popup in jQuery

Make a one time popup in jQuery for a quick project. You will have to create two functions.

  1. to set a cookie
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}

 

  1. to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}

 

Now rest is check for the cookie is set to open or not and accordingly we will show the popup here.

$(document).ready(function() {
/* if cookie doesnt exist set it to open */
if(getCookie('popup') == ''){
setCookie('popup','open',1);
}
/* if cookie exist and it is set to open */
if(getCookie('popup') == 'open'){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});

 

final code can be seen at jsfiddle

https://jsfiddle.net/shakalya/dgm0edg4/

You may also like...