How To Use Cookies With JQuery

JQuery has come and made everything easy for us, from simple toggling to otherwise complicated ajax, and whenever jQuery is not able to deliver there is always someone who has made a plugin exactly for what we need.

The Cookie Plugin

Since jQuery doesn’t have support support for cookies natively we are going to need to download a plugin. Head over to this page and copy and paste the code in a file saved as jcookie.js
Now include this file and jquery in a page like the following example.
<html>
<head>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jcookie.js"></script>
</body>
</html>
We are ready to roll.

Setting Cookies

It doesn’t take much to get started with the least options available. The syntax for making cookies with the plugin you just downloaded is the following.

A Basic Example

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

The Whole Deal

Cookies have more options of course, so this would be a cookie with all its options set. You are not obliged to used all the options.
$.cookie('cookie_name', 'cookie_value', { expires: 2, path: '/', domain: 'yourwebsite.com', secure: true });
That was easy right? But now let’s see what all these options mean:
  • expires: The value for this property is in days, the cookie will expire in two days in the previous example
  • path: The cookie is valid only for this path (folder) and sub paths (sub folders), in this example the path is the home path, so the cookie is available to all folders.
  • domain: Domain to which the cookie is available to.
  • secure: If you want to transmit the cookie or HTTPS set this value to true

Get a Cookie’s Value

Nothing could be easier in life. Try the following.
alert($.cookie('cookie_name'));

Deleting Cookies

All you have to do is set a cookies expiration date to a past time.
$.cookie("cookie_name", "any_value", { expires: -1 });

More Quickly Delete a Cookie

There is a quicker way to delete a cookie, just set its value to null. But remember you have to use the same domain and path if you had set one.
$cookie('cookie_name',null);

A Session Cookie

A session cookie is one that gets deleted when the browser is closed. To make a cookie a session cookie simply sets is expiration value to null or omit it.
$.cookie('cookie_name', 'cookie_value', { expires: null, path: '/', domain: 'yourwebsite.com', secure: true });
That’s it for this post, I hope you found this useful for your web development endeavours.

Post a Comment