rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Setting cookies with jQuery

Setting and clearing cookies with jQuery is really easy (especially when compared with regular JavaScript) but it's not included in the jQuery core and requires a plug-in. This post shows how to set, get the value of and clear cookies with jQuery.

The plug-in

Download the jQuery cookie plugin here: http://jquerybyexample.blogspot.com/2012/06/jquery-cookies-get-set-and-delete.html

Note that I am not the author of this plug-in.

Set a cookie

Setting a cookie with jQuery is as simple as this, where a cookie is created called "example" with a value of "test":

$.cookie("example", "test");

This is a session cookie which is set for the current path level and will be destroyed when the user exits the browser. To make the same cookie last for e.g. 7 days do this:

$.cookie("example", "test", { expires: 7 });

Note: the above examples will apply the cookie to the current path level.

If the page requested is http://www.bookofzeus.com/ then it will be set for the / path and will be available for all paths at the domain. If the page is http://www.bookofzeus.com/articles/ then it will be set for the /articles level and will not be accessible at / (or other path).

To explicitly make the cookie available for all paths on your domain, make sure the path is set:

$.cookie("example", "test", { path: '/' });

To limit it to a specific path instead:

$.cookie("example", "test", { path: '/articles/' });

Get the cookie's value

Getting the cookie's value is also very easy with jQuery. The following would show the value of the "example" cookie in a dialog window:

alert( $.cookie("example") );

Delete the cookie

And finally, to delete a cookie set the value to null. Setting it to e.g. an empty string doesn't remove it; it just clears the value.

$.cookie("example", null);