javascript cookies


Cookie values are stored in users browser and are accessed by the webpages. It generally stores user preference like language, color profile, user settings etc. on the site as well as usernames and passwords used in the site or any other information that the website needs for better performance and better user experience in the future. These cookies are mostly stored using server side scripts but javascript can also store and retrieve such cookies.

Javascript script for cookies first check the existence of the required cookie in the browser. If it exists, it'll use the same otherwise it'll set one and uses the same on the next page load. Cookies have an expiry date and will get destroyed on that date unless the browser overrides it with a new one. The user has the priviledge to destroy such cookies.

There are three specific operations related to cookies.

  • Set the Cookies
  • Get the Cookies
  • Delete the Cookies

Set Cookies

The first task while working with cookies would be to store the cookies in the browser. document.cookie will do the task in javascript.

function setCookie(){
  var cookieName = cookieValue;
  var ExpiryDate = new Date ();
  ExpiryDate.setTime(ExpiryDate.getTime() + (10 * 24 * 3600 * 1000));
  newExpiry = ExpireDate.toGMTString();
  document.cookie = "cookieName=" + cookieValue + ";expires="+newExpiry+";";
}

Here, we'll set the name and value of the cookie along with the number of days before the expiry of the cookie defined in seconds value. Then, we'll use the cookie object to set it on the browser. A real time example would be as shown below.

Receive User Input

The most important thing while working on cookies is to get the user input. So, we'll add an input field to get user preference on background color of a page.

<html>
<head>
  <title>Javascript Cookies Lesson</title>

</head>
<body onload="return getCookie()">

<select id="selectColor" onchange="return setCookie()">
  <option value="white">-- Select Color --</option>
  <option>red</option>
  <option>green</option>
  <option>blue</option>
</select>

</body>
</html>

The form also holds an event handler that triggers the function setCookie() on change of its value. Now, we'll add the same function.

function setCookie(){
  var color = document.getElementById('selectColor').value;
  var ExpireDate = new Date ();
  ExpireDate.setTime(ExpireDate.getTime() + (10 * 24 * 3600 * 1000));
  newExpiry = ExpireDate.toGMTString();
  document.bgColor = color;
  document.cookie = "color=" + color + ";expires="+newExpiry+";";
}

So, the color value is retrieved from user input and used to style the background color of the page. Moreover, we also made the select form display the same selection after the cookie is set. Lets make the same preferences exist the next time the user visits this page. Keep in mind, Google Chrome doesn't allow local level cookies.

Get Cookies

The function getCookie() will check for the existence of the defined cookie name and its value in the browser. If the cookie exists, it'll retrieve the values and use it.

function getCookie(){
  if(document.cookie.length > 0){
    var cookies = document.cookie.split("=");
    var cookieName = cookies[indexnumber];    
  }
}

This function getCookie() will check for the cookies in the browser. If the cookie is found, it will return the value along with the set date as well as expiry date. We can add further processing code blocks to define how we want to use those cookies. Here's the real time example.

function getCookie(){
  if(document.cookie.length > 0){
    var cookie = document.cookie.split("=");
    var color = cookie[1];
    document.bgColor = color ;
    document.getElementById('selectColor').value = color;
  }else{
    document.bgColor = "white" ;
    document.getElementById('selectColor').value = "white";
  }
}

Here, we checked for the existence of the cookie and split the cookie string on the basis of = symbol. Since the color value was in array index [1], we used the index value 2. You should alert the result after split before calling the index number. Then we applied the same to the document background as well as displayed them in the select option. Since, we are loading this function automatically on page load, we also added a default background color and select option value to display in case the cookie is not set.

Delete Cookies

The process of deleting cookies from the browser is half the process of retrieveing one and half the process of storing one. At first, we'll check the existene of the cookie and then retrieve it. Then we'll follow the process of setting one. The only difference is the expiry time which should be a time period of the past or the exact moment when the function is being triggered.

function deleteCookie(){
  if(document.cookie.length > 0){
    var cookies = document.cookie.split("=");
    var cookieName = cookies[indexnumber];   
    document.cookie = "cookieName=" + cookieValue + ";expires="+Date()+";";
    location.reload(); 
  }
}

So, we retrieved the cookie name and value from the browser and then set it again but this time with the current time value that'll expire within a second. Here's a real time example.

function delCookie(){
  if (document.cookie.length > 0){
    var cookies = document.cookie.split("=");
    var color = cookie[1];
    document.cookie = "color=" + color + ";expires=" + Date() +";";
    location.reload();
  }
}