Recent Posts

How to: Set/unset cookie with jQuery

This can be done with the plugin:

https://github.com/carhartl/jquery-cookie

You can then do:

$.cookie("test", 1);
To delete:

$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.

To cover all the options:

$.cookie("test", 1, {
   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  : 'jquery.com',  //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("test");
You may wish to specify the path parameter if the cookie was created on a different path to the current one:

var cookieValue = $.cookie("test", { path: '/foo' });

No comments:

Post a Comment