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.

Starting

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.

[html]
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<a href="http://jquery.cookie.js">http://jquery.cookie.js</a>
<a href="http://general.js">http://general.js</a>
[/html]

In terms of HTML this snippet is really simple:

[html]
<ul>
  <li>
    <h2>
      <a href="#basic" id="basic">Basic</a>
    </h2>
  </li>
<li>
  <h2>
    <a href="#intermediate" id="intermediate">Intermediate</a>
  </h2>
</li>
<li>
  <h2>
    <a href="#advanced" id="advanced">Advanced</a>
  </h2>
</li>
</ul>
<a href="#" id="showCookie">Show cookie</a>
<a href="#" id="deleteCookie">Delete cookie</a>
<input disabled id="verbose" type="text" />
[/html]

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:

[js]
jQuery(document).ready(function(){
  //code goes here
)};
[/js]

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:

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

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:

[js]
$( '#' + $.cookie( cookieName ) ).addClass( 'selected' );
[/js]

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.

[js]
$( '.htabs a' ).click( function( e ) {
e.preventDefault();
$( '#' + $.cookie( cookieName ) ).removeClass( 'selected' );
[/js]

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.

[js]
$.cookie(cookieName, $(this).attr("id"), cookieOptions);
[/js]

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

[js]
     $("#" + $.cookie(cookieName)).addClass("selected");
});
[/js]

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.

[js]
$("#showCookie").click(function(e){
  e.preventDefault();
  $("#verbose").val("Cookie value is " + $.cookie(cookieName) + ".");
});
[/js]

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.

[js]
$("#deleteCookie").click(function(e){
  e.preventDefault();
  $("#verbose").val("Cookie 'level' with value "" + $.cookie(cookieName) + "" removed.");
  $("#" + $.cookie(cookieName)).removeClass("selected");
[/js]


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

[js]
$.cookie(cookieName, null);
[/js]

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:

[js]
if (value === null) {
  value = '';
  options.expires = -1;
}
[/js]


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

[js]
$.cookie(cookieName, $(this).attr("id"), cookieOptions);
[/js]


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:

[js]
   });
});
[/js]

Play with the demo, click the labels, output the value, reload the page, close the tab and open it again, delete the cookie, etc.

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

Advertisements

16 thoughts on “Using cookies with jQuery”

  1. @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.

  2. Hi,
    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:
    e.preventDefault();
    $(“#” + $.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?

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

Leave a Reply