How to Set a Cookie using jQuery Programming 27 AUG 2013

jquery-logoIf jQuery is your javascript manipulation library of choice, then you would be pretty pleased that developer Klaus Hartl took the time and whipped up his excellent jquery-cookie plugin, thereby making the act of setting or retrieving browser cookies in your jQuery JavaScript a snap!

To set the value of a cookie is pretty simple, just pass along a key and a value, and as expected, you can make it a little more verbose by including a selection of all the standard cookie stuff like expiry date, path, or domain.

In action:

$.cookie("mycookie", "on!");

//Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("mycookie", "on!", { expires : 10 });

Note, if the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.

This snippet covers most of the options in setting up a cookie that are available to you:

$.cookie("mycookie", "on!", {
   expires : 10,           //expires in 10 days

   path    : '/',          //The value of the path attribute of the cookie 
                           //(default: path of page that created the cookie).

   domain  : '',  //The value of the domain attribute of the cookie
                           //(default: domain of page that created the cookie).

   secure  : true          //If set to true the secure attribute of the cookie
                           //will be set and the cookie transmission will
                           //require a secure protocol (defaults to false).

To read back the value of the cookie:

var cookieValue = $.cookie("mycookie");

//You may wish to specify the path parameter if the cookie was created on a different path to the current one:
var cookieValue = $.cookie("mycookie", { path: '/view' });

To delete a cookie:


Right, that should now be enough to get you up and running!

Related Link:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.