Boosting Ezine Subscribers With a Popup Window - How setCookie Is Used
(Page 3 of 4 )
The setCookie function shown above accepts the name, value, path and expiry date of a cookie to set. It's used like this:
setCookie('myCookie', 'myValue', '', '');This would set a cookie named "myCookie", which would contain the value "myValue". The last two arguments to the setCookie function are the cookie path and its expiry date. As you can see, you can leave the last two arguments as ''. The setCookie function will use default values if they are empty.
The getCookie function accepts the name of a cookie to retrieve, and returns its value if it exists:
var c = getCookie('myCookie');"c" would now contain "myValue".
Displaying the Ezine Signup WindowNow that we can get and set cookies, we're ready to actually use the setCookie and getCookie functions. We will create a function that will check whether or not a specific cookie is set. If it is, then we will not display the ezine popup window. On the other hand, if there is no cookie set, we will display the ezine popup page and set a cookie to indicate that the signup form has been shown. The function is very simple, and looks like this:
function doPopup()
{
var ezine = getCookie('popupShown');
setCookie('popupShown', 'true', '', '');
if(ezine == '')
{ // Show the popup window
window.open('ezine.html', 'ezineWin', 'width=500,height=400');
}
}The doPopup function starts by creating a new variable named ezine, which will contain the value of the "popupShown" cookie. Irrespective of whether or not the getCookie() function returns a value, we set the "popupShown" cookie. Our "setCookie" function automatically sets a period of time for which the cookie will persist. As you can see from the code snippet below (taken from the setCookie function we created above), the default is 6 months:
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 6);
cookieExpires = nowDate.toGMTString();By resetting the "popupShown" cookie each time the user visits this page, we're making sure the popup is never displayed again as long as they continue to visit the site at least once every six months.
The most popular times to display the actual signup form are when the user jumps to another page or exits your site. Both of these events trigger the onUnload event handler. We need to tell the browser to call the doPopup function when this occurs so we modify the <body> tag like this:
<body onUnload="doPopup()">Now, if the visitor jumps to another page on our site, or closes the browser window, then our ezine popup will be displayed in a new window.
Next: Conclusion >>
More JavaScript Articles
More By Mitchell Harper