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)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
