Jookie: a jQuery JSON cookie handler

August 2009

There are a million JavaScript cookie handling libraries out there and I do not profess that this one is any better than the others. However, being a firm believer in 'learning by doing', here is my offering.

Jookie creates, reads, updates and deletes cookies. It stores them as stringified JSON which, in plain English, means that you can store and retrieve complex JavaScript objects very easily. Because this plugin uses JSON, it relies on Douglas Crockford's open source JSON parser and stringifier which I have appended to my source code. If you already use Mr Crockford's code in your application, you'll probably want to strip this additional definition out.

Initialising a cookie

"Initialise" doesn't necessarily mean "create", rather it means "prepare for use". If the cookie didn't previously exist, then yes, it would be created too. Every time you call a Jookie function, pass in an indentifier to determine which cookie to read from or modify.

// initialise a cookie that lives for 60 minutes
$.Jookie.Initialise("myCookieName", 60);

// initialise a cookie that lives for the length of the browser session
$.Jookie.Initialise("myOtherCookieName", -1);

Getting and setting values

Hopefully this bit is really straightforward. Because the data is stringified when saved and parsed when retrieved, values "get" from Jookie will be the same as when the were "set".

// retrieve a value from the cookie
$.Jookie.Get("myCookieName", "myVariableName");

// set a value to the cookie
$.Jookie.Set("myCookieName", "myVariableName", "My Example Value");

// delete a single value within the cookie
$.Jookie.Unset("myCookieName", "myVariableName");

Deleting a cookie

I'm guessing you're spotting a pattern by now...

$.Jookie.Delete("myCookieName");

Debugging

I've added a simple "Debug" function which pops up an alert() box with the cookie's contents and some information about it.

$.Jookie.Debug("myCookieName");

You are welcome to download and use my plugin which is distributed under the MIT licence. If you're interested to see other jQuery work I've done, check out my JAWStats web analytics project.

Jon Combe