Gilles Ruppert

a.k.a. elduderino78

JavaScript Cookies Made Easy

Here is another little script that makes my life a bit easier. It consists of 3 methods that makes working with cookies very straight forward. This script is built on the shoulder of giants: PPK from Quircksmode was the man who did the hard work.

However, rather than creating 3 methods that sit in the global namespace, I wanted to use a singleton object that would only add 1 global variable. Since there is no need for private methods, the object literal pattern is appropriate. In my opinion the names of the methods make it very straight forward to use. Good names mean less looking up, mean less mistakes, mean faster development. Your Technical Project Manager will love you for it :-)

1
2
3
4
5
6
7
8
// To create/set a cookie:
cookie.set('name', 'value, 234); // last argument is number of days until expiry. If none is provided, it will get deleted when the browser is closed

// To get the cookie value:
cookie.get('name');

// To delete the cookie:
cookie.erase('name');

As always, you can download the latest version from my svn repository