Javascript – How to set/unset a cookie with jQuery

cookiesdomjavascriptjquery

How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?

Best Answer

Update April 2019

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

Basic examples:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

See the docs on github for details.


Before April 2019 (old)

See 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");

UPDATE (April 2015):

As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.