Setting cookies with jQuerySetting cookies with jQuery

Posted June 9th, 2009 in Javascript (Updated January 24th, 2012)

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 plugin

Download the jQuery cookie plugin here: https://github.com/carhartl/jquery-cookie
Note that I am not the author of this plugin.

Set a cookie

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

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

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", "foo", { expires: 7 });

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

If the page requested is http://www.example.com/file.html then it will be set for the / path and will be available for all paths at the domain. If the page is http://www.example.com/subpath/file.html then it will be set for the /subpath level and will not be accessible at / (or /otherpath etc).

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

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

To limit it to a specific path instead:

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

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);

Looping through the cookies

My next Javascript post looks at how to loop through cookies with Javascript to show all the currently set cookies.

Cookies and domains

Refer to my "Cookies and Domains" post for more information about being able to set the domain of a cookie and how it relates to subdomains.

Cookies and paths

I touched on the issue with cookies and setting the path in the post above. As of the last update of this post (November 5th 2010), I am intending to write another post shortly which covers this topic in more detail.

Related posts:

Comments

blog comments powered by Disqus