Skip to content
Advertisement

How do I set/unset a cookie with jQuery?

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

Advertisement

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:

JavaScript

See the docs on github for details.


Before April 2019 (old)

See the plugin:

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

You can then do:

JavaScript

To delete:

JavaScript

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

JavaScript

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:

JavaScript

To read back the value of the cookie:

JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement