Working with Cookies in jQuery

Share this article

Cookies are the most used technology for storing data on the client side. My previous article, How to Deal with Cookies in JavaScript, explained how to perform CRUD operations with cookies using raw JavaScript. This article turns to jQuery, and will guide you through the use of jquery.cookie, a plugin which makes cookie processing simple. This article assumes that the reader is familiar with the content from the previously cited post, or at least has a basic understanding of cookies. With that said – let’s get started.

Installing jquery.cookie

The first thing you need to do is download jquery.cookie from its repository on GitHub. Once you have the file jquery.cookie.js, you simply need to add it in your page(s). Be aware that, being a jQuery plugin, you have to include it after the jQuery library. Your pages should have a piece of code that resembles the following:
<head>
  <script src="path/to/jquery.js"></script>
  <script src="path/to/jquery.cookie.js"></script>
</head>

The Methods

To both create and retrieve a cookie, jquery.cookie uses the same method, cookie(), but with a different number of parameters. To create a cookie you need to pass in two required parameters, the name and value of the cookie, respectively. You can pass a third, optional, parameter that is an object literal containing some additional options. These options are path, domain, expires, and secure. It’s worth noting that these options can be set locally, when you call the cookie() method, or globally through the $.cookie.defaults
object. The options set using the former, take priority over those set using the latter. To see how cookies are created, let’s look at a few examples. The following example tracks the number of times the user has visited a website:
$.cookie("visits", 10);
This example stores the user’s favourite city, as well as specifying the domain and the path where the cookie can be read and written:
$.cookie("favourite-city", "London", {path: "/", domain: "jspro.com"});
This example stores the name of the user. This particular cookie expires on October 29, 2013 at 11 a.m., and can only be sent through a secure connection.
$.cookie("name", "Aurelio", {expires: new Date(2013, 10, 29, 11, 00, 00), secure: true});

Retrieving Cookies

Retrieving a cookie is extremely easy. You just pass a single parameter, the name of the cookie, to retrieve it, as shown by the following examples: To retrieve the number of times the user has visited the website:
console.debug($.cookie("visits")); // print "10"
To retrieve the user’s favourite city:
console.debug($.cookie("favourite-city")); // print "London"
To retrieve the name of the user:
console.debug($.cookie("name")); // print "Aurelio"

Delete a Cookie

Now you know how to create and retrieve a cookie. The last thing you need to know is how to delete a cookie using the removeCookie() method. It returns true if the requested cookie is found, and false otherwise. Be aware that when you want to remove a cookie, you need to pass in the same options, such as path and domain
, otherwise the operation will fail. Now, let’s see a couple examples of the removeCookie() method. To remove the cookie storing site visits:
$.removeCookie("visits"); // successfully deleted
To remove the cookie storing the user’s favourite city:
$.removeCookie("favourite-city", {path: "/", domain: "jspro.com"}); // successfully deleted
Next, we attempt to remove the cookie storing the user’s name. This example fails because the secure value was not specified.
$.cookie("name"); // fails because the secure value is missing

Conclusions

This article showed you how to manage cookies using jquery.cookie, a jQuery plugin. It solves many problems by abstracting cookie implementation details into a few simple, flexible methods. In case you need further clarification or additional examples, please refer to the official documentation. And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like jQuery: Novice to Ninja: New Kicks And Tricks. Comments on this article are closed. Have a question about jQuery? Why not ask it on our forums?

Frequently Asked Questions (FAQs) about jQuery Cookies

How can I set a cookie with jQuery?

Setting a cookie with jQuery is quite simple. You can use the $.cookie function to set a cookie. Here is an example:

$.cookie('cookie_name', 'cookie_value');

In this example, ‘cookie_name’ is the name of the cookie and ‘cookie_value’ is the value you want to store in the cookie. This will create a cookie that expires when the browser session ends. If you want to set a specific expiration date, you can add an options object as the third parameter:

$.cookie('cookie_name', 'cookie_value', { expires: 7 });

This will create a cookie that expires in 7 days.

How can I read a cookie with jQuery?

Reading a cookie with jQuery is also straightforward. You can use the $.cookie function again, but this time without the second parameter. Here is an example:

var cookie_value = $.cookie('cookie_name');

In this example, ‘cookie_name’ is the name of the cookie you want to read. The function will return the value of the cookie.

How can I delete a cookie with jQuery?

To delete a cookie with jQuery, you can use the $.removeCookie function. Here is an example:

$.removeCookie('cookie_name');

In this example, ‘cookie_name’ is the name of the cookie you want to delete. This will remove the cookie from the browser.

Can I set secure cookies with jQuery?

Yes, you can set secure cookies with jQuery. Secure cookies are only sent over HTTPS connections. To set a secure cookie, you can add an options object with the ‘secure’ property set to true as the third parameter to the $.cookie function:

$.cookie('cookie_name', 'cookie_value', { secure: true });

This will create a secure cookie.

Can I set cookies that are accessible on multiple paths?

Yes, you can set cookies that are accessible on multiple paths. By default, cookies are only accessible on the path where they were set. To set a cookie that is accessible on multiple paths, you can add an options object with the ‘path’ property set to the desired path as the third parameter to the $.cookie function:

$.cookie('cookie_name', 'cookie_value', { path: '/' });

This will create a cookie that is accessible on all paths.

Can I set cookies that are accessible on multiple domains?

Yes, you can set cookies that are accessible on multiple domains. By default, cookies are only accessible on the domain where they were set. To set a cookie that is accessible on multiple domains, you can add an options object with the ‘domain’ property set to the desired domain as the third parameter to the $.cookie function:

$.cookie('cookie_name', 'cookie_value', { domain: '.example.com' });

This will create a cookie that is accessible on all subdomains of example.com.

How can I check if a cookie exists with jQuery?

You can check if a cookie exists with jQuery by reading the cookie and checking if the returned value is not undefined. Here is an example:

var cookie_exists = typeof $.cookie('cookie_name') !== 'undefined';

In this example, ‘cookie_name’ is the name of the cookie you want to check. The variable ‘cookie_exists’ will be true if the cookie exists and false otherwise.

Can I set cookies with custom expiration dates with jQuery?

Yes, you can set cookies with custom expiration dates with jQuery. To set a cookie with a custom expiration date, you can add an options object with the ‘expires’ property set to a Date object as the third parameter to the $.cookie function:

var date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
$.cookie('cookie_name', 'cookie_value', { expires: date });

This will create a cookie that expires in 7 days.

Can I set cookies with custom expiration times with jQuery?

Yes, you can set cookies with custom expiration times with jQuery. To set a cookie with a custom expiration time, you can add an options object with the ‘expires’ property set to a number representing the number of days until the cookie expires as the third parameter to the $.cookie function:

$.cookie('cookie_name', 'cookie_value', { expires: 0.5 });

This will create a cookie that expires in 12 hours.

Can I set cookies that are only sent over HTTP with jQuery?

Yes, you can set cookies that are only sent over HTTP with jQuery. These cookies are not accessible via JavaScript, which can help prevent certain types of cross-site scripting attacks. To set a cookie that is only sent over HTTP, you can add an options object with the ‘httpOnly’ property set to true as the third parameter to the $.cookie function:

$.cookie('cookie_name', 'cookie_value', { httpOnly: true });

This will create a cookie that is only sent over HTTP. Please note that this option can only be set server-side, so you cannot actually set ‘httpOnly’ cookies with jQuery.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

IntermediatejQueryplugins
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week