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: https://plugins.jquery.com/cookie/
Note that I am not the author of this plugin.

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

 

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

 

0 Shares:
Leave a Reply

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

one × three =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

Text Resizing With jQuery

Want to allow visitors to increase or decrease the text size (font size) on your website? I’m going to show you how - using jQuery (a great JavaScript library).

qTip2 – Advanced jQuery Tooltip Plugin

qTip2 plugin can display the tooltip in any position wanted, plays nicely with image maps and they can be set to follow any element (handy for drag 'n' dropped and animated items) or mouse.