Allground - Responsive Fullscreen Backgrounds for WordPress with images, YouTube videos, Google Maps and self hosted videos

Using cookies with jQuery

Cookies aren’t just tasty and chocolate-flavoured. They can also store useful information for your users to have a better experience on your site. They are jQuery flavoured too. In this tutorial we will learn how to use jQuery and cookies to store some user preferences in a cookie to display an specific content to the user. So, grab one of your favourite cookies and read on.


What we are going to do is just a panel with a series of labels. Each time you click one of them, it will be highlighted and the name of the selected label will be stored in a cookie in your computer through your browser. After that, you can use two buttons to display the value that the cookie currently contains or simply delete the cookie.

In addition, look at the application the first time you load the demo page. None of the labels are selected. Now, after you select one, you can reload the page and see that the label you selected before is still selected. If you delete the cookie now it will be deselected. After reloading the page you will see that no label has been selected. Ok, time to watch it in action. Try it, play around

Visit demo of Using cookies with jQuery

Handling cookies with jQuery

We are going to use jQuery to handle our cookies and we will also be using a free jQuery plugin that specifically deals with cookie storage, aptly named, Cookie.

Download Cookie plugin from jQuery projects area.

Cookie is a simple plugin with only one function, Cookie(). With this function you will write, get and delete cookies on your computer.

The markup

After including the jQuery library, we will include the jquery.cookie.js plugin in our HTML. After that, include your JavaScript file or just type it in a <script> tag.

<script type="text/javascript" src=""></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="general.js"></script>

In terms of HTML this snippet is really simple:

      <a href="#basic" id="basic">Basic</a>
      <a href="#intermediate" id="intermediate">Intermediate</a>
      <a href="#advanced" id="advanced">Advanced</a>

<a href="#" id="showCookie">Show cookie</a>
<a href="#" id="deleteCookie">Delete cookie</a>
<input disabled id="verbose" type="text" />

We’re writing three labels, a couple of anchors and an input, to output the state of the cookie. The CSS is irrelevant since it is only used to highlight the selected label applying the .selected class. Let’s jump straight to the fun part.

jQuery Cookies – Creating the cookie

So, first things first, add the usual snippet to execute our jQuery when the document is ready:


     //code goes here


Now, let’s initialize a couple of variables to use them through our code. These are the cookie’s name and a set of options to pass on the cookie function: expiration time and a path, which can be a url from a page. there are other arguments but for the sake of clarity, we will only use these two:

var cookieName = 'level';
var cookieOptions = {expires: 7, path: '/'};

Next, let’s see if our cookie has its value set. If it doesn’t, it’s ok, never mind. But if it does, add the .selected class to the label whose ID is stored in the cookie. We use the cookie function with a single parameter, the name of the cookie whose value we want to retrieve:

$("#" + $.cookie(cookieName)).addClass("selected");

We will be building a click event now. The preventDefault() function is a standard jQuery procedure to prevent anchor jumping on the browser when you click a link. When a user clicks the label (which is actually an anchor), we will remove the .selected class from the label where it’s currently applied and add it to the clicked label.

$(".htabs a").click(function(e){
$("#" + $.cookie(cookieName)).removeClass("selected");

Time to create a cookie and assign it a value. First argument is the cookie name, which is level, the second one is the value that we will assign to it, which is the name of the label. We will also pass the options set that we wrote before.

$.cookie(cookieName, $(this).attr("id"), cookieOptions);

Now let’s simply add the .selected class to the label:

     $("#" + $.cookie(cookieName)).addClass("selected");

jQuery Cookies – Retrieving and displaying the cookie’s value

We now want to output the value of our cookie. All the we need to do is to call cookie function without any other parameter than the name of the cookie we want to inspect. When the #showCookie button is clicked, we will write the value currently stored in the cookie on the #verbose field.

  $("#verbose").val("Cookie value is " + $.cookie(cookieName) + ".");

jQuery Cookies – Deleting the cookie

Now we reach to the point when we want to delete the cookie. So, when the #deleteCookie button is clicked we will output on the #verbose field the name of the cookie being deleted. Then we remove the .selected class from where it’s currently applied.

  $("#verbose").val("Cookie 'level' with value \"" + $.cookie(cookieName) + "\" removed.");
  $("#" + $.cookie(cookieName)).removeClass("selected");

Finally we will delete the cookie, and this is an interesting step. The code goes simply like:

$.cookie(cookieName, null);

Ok, no big deal right? This is correct. In fact, this is the way shown on the Cookie plugin example page. However,
when you do this and pass in the cookieOptions variable as a third argument, the expires variable of cookieOptions is set to -1. Inspect the code for jquery.cookie.js and you will find this:

if (value === null) {
  value = '';
  options.expires = -1;

Why is this important? because if you pass cookieOptions as a third argument and were to create a new cookie right now using

$.cookie(cookieName, $(this).attr("id"), cookieOptions);

it would not work, because cookieOptions.expires has been set to -1, which according to the description found on the plugin:

If a negative value is specified (e.g. a date in the past), the cookie will be deleted.

That’s it, we’ve reached the end:


Play with the demo, click the labels, output the value, reload the page, close the tab and open it again, delete the cookie, etc.
Here’s the complete code for close inspection.

I hope you’ve enjoyed this and see you next time for more jQuery goodness.

“Using cookies with jQuery” received 16 comments! Add yours.

  1. Pablo Mendoza July 15th, 2010

    Thanks Elio! :D

  2. Marcell Purham | Webdevtuts July 17th, 2010

    Where was this post last week haha. Great post!

  3. Tonyg July 18th, 2010

    Good joob man.

  4. links for 2010-07-19 | Folks Pants July 19th, 2010

    [...] Using cookies with jQuery | jQuery | ilovecolors (tags: jquery cookies) [...]

  5. yellowww July 22nd, 2010

    Very good post!

  6. Top Worthwhile Tutorials of the Week – #6 | AEXT.NET MAGAZINE August 1st, 2010

    [...] function you will write, get and delete cookies on your computer.You can see this great tutorial here.Create an iPod Nano in IllustratorI don’t usually include the graphic design tutorial in this [...]

  7. Top Worthwhile Tutorials of the Week – #6 | Digital information Ebooks/Books and Software August 7th, 2010

    [...] You can see this great tutorial here. [...]

  8. kevin August 11th, 2010

    How could I store cookies in an array. The selected item will come from different pages?


  9. Using cookies with jQuery | WickedBrilliant August 15th, 2010

    [...] always wished jQuery had built in cookie support. Here’s a nice example using the cookie plugin. Filed under Interesting [...]

  10. InternetFluent November 20th, 2010

    @kevin …why don’t you store the array in a cookie ? I store different pieces of data separated by “:” and split the string and turn it into an array when I need to.

  11. Titus January 21st, 2011

    Simple plugin but powerfull!!

  12. Raymond March 14th, 2011

    It’s more useful to use than the other one who has a lot of functions that you couldn’t understand

  13. hello May 4th, 2011


  14. Chris May 4th, 2011

    this is a great tutorial and I’m just trying to make it work for my website. Other than your option where only one item in the list can be selected, I’d like to achieve that all items will stay selected. E.g. click on “#link1″ will select “#link1″, link on “link2″ will select “link2″ in a addition to “#link1″ etc. I achieved this by deleting the following 2 lines:
    $(“#” + $.cookie(cookieName)).removeClass(“listeclick”);

    But when I click on the “Delete cookie” button, only the very last highlighted link will be removed. How can I delete all highlights at the same time?

  15. tiagoa June 3rd, 2011

    To delete a cookie this code: $.cookie(‘cookieName’, null) don’t works, but I tryed it: $.cookie(‘cookieName’, ”) and it works.

  16. Virendra May 14th, 2012

    Great post..

    But this jQuery plugin doesn’t supports JSON cookies along with the regular cookies.

    There is another plugin called Dough which is just amazing. Check this post..

Leave a comment