Previously I've explained how you can use pop-up windows on your website, launching them from a short piece of Javascript.
But, of course, many users aren’t keen on pop-ups, even if they remind them of something quite important.
So it’s a compromise and sometimes part of that compromise might be not displaying a pop-up for a certain amount of time, such as seven days. A solution for handling that is to use cookies.
The cookie monster
Some people have an aversion to cookies, mistakenly believing that they can
allow your computer to send private information to a website.
That’s not really the case they can only send back to a website some information that it sent to your computer in the first place, like your user id on the site, or something that helps them see which user has looked at which pages.
A cookie consists of a few bits of data, stored as text on your computer. There’s a name, a value for the data perhaps your id for the site, or a set of preferences, or simply ‘true’ or ‘false’; anything that can be saved as text an expiry date, a path and a domain.
Those last three are the elements that we’re interested in here.
The Expiry date is the date on which the browser can safely discard the cookie. If it’s not set, then the cookie is a ‘session cookie’ which means it’ll disappear when you quit the browser, otherwise it’ll be stored until the date, which is specified in a fairly strict format.
The path restricts the cookie to a section of your website. If it’s set to ‘/’ then the cookie will be returned to the web server for every page on your site. Set it to, say, ‘/shop’ and only pages on your site with URLs starting ‘/shop’ will see its value.
The domain works in a similar way, but can restrict the cookie to part of your domain, or those higher up. If you have a domain mysite.example, then setting the cookie to that would allow it to be seen on websites at forums.mysite. example, or www.mysite.example.
Set it to forums.mysite.example, and the main website won’t get the cookie, either.
Cookies in Javascript
So, now you know how cookies work, how are they handled in Javascript? Not
elegantly would be one way of putting it. In a PHP script, and other languages,
you can easily see the value of any single cookie. Not so in Javascript.
First, though, how about setting a cookie? All you do is set a value called document.cookie to whatever you want, like this, which sets a cookie called ‘popupshown’ to the value ‘true’:
document.cookie = ‘popupshown=true; expires=Thu, 14 Feb 2007 12:00:00
UTC; path=/’
You could add a domain too it’s just another parameter, which could follow the path option, after a semicolon. Omit the expiry information and you just get a session cookie; set it to a date in the past and you’ll delete the cookie.








