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 cookiein 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 = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></ 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:
< 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" /> |
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:
jQuery(document).ready( function (){ //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 thecookie 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){ e.preventDefault(); $( "#" + $.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 cookiefunction 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.
$( "#showCookie" ).click( function (e){ e.preventDefault(); $( "#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.
$( "#deleteCookie" ).click( function (e){ e.preventDefault(); $( "#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, theexpires 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:
That’s it, we’ve reached the end:
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.
No comments:
Post a Comment