November 30, 2011

jQuery: Setting cookies

Setting and clearing cookies with jQuery is really easy 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
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 “mycookie” with a value of “100”:

$.cookie(“mycookie”, “100”);

 

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. 10 days do this:

$.cookie(“mycookie”, “100”, { expires: 10 });

 

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(“mycookie”, “100”, { path: ‘/’ });

 

To limit it to a specific path instead:

$.cookie(“mycookie”, “100”, { 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(“mycookie”) );

 

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(“mycookie”, null);

 

JavaScript , jQuery # ,
Share: / / /

You might also like

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This