JavaScript Cookies

If like me you usually create your cookies using a server scripting language like PHP, you may find that using JavaScript for cookies is simple.

Im going to show you how to create, edit, delete and read cookies using only JavaScript.

Creating JavaScript Cookies:


function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

As you can see the function createCookie requires 3 values:


  • name = the name you want to give the cookie

  • value = the value the cookie will hold

  • days = the number of days you want the cookie to last [can be up to 30 days])

Deleting a JavaScript Cookie:


function eraseCookie(name) {
  createCookie(name, "", -1);
}

The above function eraseCookie requires the name of the cookie you want to delete. It simply marks the expire date as yesterday.

Reading a JavaScript Cookie:


function readCookie(name) {
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return "";
}

readCookie does just that, provide the function with the name of the cookie you want to read and it will return its value.

So lets put all that together now and write the contents of the cookie out to the screen.



 
  JavaScript Cookies

  
   
   
Change value

In the above code we simply create the cookie using body onLoad and calling the makeCookie() function.
When we click the link 'Change Value' we are calling the JavaScript function editCookie() which deletes the current cookie and recreates a new one with the same name but new value.

That's all there is to it, easy peasy!! :-)

1 Comment on JavaScript Cookies

  1. T. Orion says:

    Thanks for the javascript cookie tutorial… definitely came in handy! Nice work!