Cookies with jQuery

July 6, 2010

Being able to set and read cookies asynchronously can be a great feature in many aspects of a web app. If you are looking for such a feature you probably already have jQuery attached to your app. All you need now is the jQuery Cookie plugin. You can pick that up at Here.

Once you have that attached in your files, you can easily start setting and reading cookies.

Set Cookie

$.cookie("cookie_name", "your_value");

Adding Options

$.cookie('cookie_name', 'your_value', { expires: 10, path: '/basepath/for/cookies', domain: 'yourdomain.com', secure: true });

The line above lets you set multiple parameters to the cookie. The above cookie would expire in 10 days and the path will set the area of your site the cookie will work.

If you were to do the same action in strictly javascript you would have to run more detailed code like:

document.cookie = "cookie_name=your_value; expires=16/07/2010 00:00:00; path=/basepath/for/cookies; domain=yourdomain.com";

jQuery is slightly easier to use in this regard but is even better when retrieving the cookie values.

Read Cookie

$.cookie("cookie_name");

Removing a cookie is also easy but they way you do it may not be the first guess a programmer would try without consulting documentation.

Remove Cookie

$.cookie("cookie_name", null);

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive