Setting cookies with jQuery
Posted June 9th, 2009 in Javascript
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: http://plugins.jquery.com/project/Cookie
Set a cookie
Setting a cookie with jQuery is as simple as this, where we are creating a cookie called "example" with a value of "foo":
$.cookie("example", "foo");
This is a session cookie 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 });
The above examples will apply the cookie to the root level. If you wanted to make it apply only to e.g. /admin and make it last 7 days you can do this:
$.cookie("example", "foo", { path: '/admin', expires: 7 });
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 jQuery post will look at how to loop through cookies with jQuery to show all the currently set cookies.
Related posts:
- Get all cookies with Javascript (Friday, June 12th 2009)
- Find the index of the element that was clicked with jQuery (Tuesday, May 19th 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Add an offsite link icon after external links with jQuery (Saturday, March 28th 2009)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
