Setting and Getting Cookies with JavaScript
Author: Richard Francis | Filed under: User experience, Web DevelopmentWhy use cookies?
Using cookies can be very useful from a user experience perspective. They are used to save small amounts of data onto the users’ machine, enabling the site to use this data next time the user visits. This is particularly useful if you have an age-gate (maybe for a movie or an alcoholic brand) but you don’t want to confront the user with this each time they visit if they have previously confirmed a valid date of birth. In this situation, you can set a cookie on their machine (named ‘ageCookie’ for example) and give it a value of ‘true’ or ‘false’. You can then detect the value of this cookie next time they visit (if it exists) and perform the necessary actions.
Show me the code!
It’s simple, there are 2 core functions you will need: setCookie() and getCookie(). They are pretty self-explanatory, one sets a cookie on the users’ machine and the other gets a cookie.
Here is the code:
// This function will get a cookie from the users' machine
function getCookie(theName) {
var nameEQ = theName + "=";
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) return c.substring(nameEQ.length,c.length);
}
return null;
}
// This function will set a cookie on the users' machine
function setCookie(theName, theValue, theDays) {
if (theDays) {
var date = new Date();
date.setTime(date.getTime()+(theDays*24*60*60*1000));
var expires = "; expires="+date.toLocaleString();
}
else var expires = "";
document.cookie = theName+"="+theValue+expires+"; path=/";
}
Once you have this code in your page, you just need to call these functions and pass the parameters. For example: setCookie('ageCookie', 'ok', 365);. Notice how I pass a value of 365 for theDays parameter. This will ensure that the cookie will stay on the users’ machine for up to 1 year (given that they never clear their cookies).
Things to remember/useful tips
- When testing the functions remember to enable cookies on your machine.
- It is always useful to use a debugger such as the Web Developer Toolbar or Firebug, both for Firefox. These add-ons will enable you to view the cookies on your machine, edit their values, and remove them.
Tags: Cookies, Javascript
































Leave a Reply