Setting Cookies with JQuery

I've never really used or dealt with browser cookies before because I felt like it was some complicated, advanced technique that required intricate knowledge of how browsers and sessions work.

Today at work, I was given a task that involved setting, checking, and removing cookies for our web application, but I pleasantly found that it was an almost laughably easy task with my best friend JQuery.

Download the Plugin

First, you need to download the handy JQuery cookie plugin here: JQuery Cookie Plugin!

Setting Cookies

To set cookies, all you need to do is type in the following in Javascript:

$.cookie("cookieName", "cookieValue");

This default cookie creation links this particular cookie to the session and it will be deleted at the end of some amount of time or if the user closes the browser, etc. If you want to have a cookie stay for a defined amount of time instead of linking it to the session, you can do something like this:

$.cookie("cookieName", "cookieValue", { expires: 1 }); // 1 day

The expiration parameter's unit is in days so if you want to, say, set a cookie for only 30 minutes you'll have to do something a little tricker (I found this cool tip on Stack Overflow):

var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
$.cookie("example", "foo", { expires: date });

You can also set the path and domain of the cookie (default is the current path and current domain):

$.cookie("cookie", "1", { domain: "domain.com", path: "/" });

Reading Cookies

It's really easy to read back a cookie's value:

$.cookie("cookieName");

Really, that's it!

Deleting Cookies

Finally, to delete a cookie just set it to null:

$.cookie("cookieName", null);

Note that by default, this plugin won't let you delete a cookie from another domain so you'll have to explicitly specify the domain and path:

$.cookie("cookieName", null, { domain: "domain.com", path:"/");