jQuery Cookies: Get, Set, Update, Delete

Create, read, update and delete cookies with jQuery, including expiry and path options.

  • The jQuery Cookie plugin by Klaus Hartl (available on GitHub) makes it easy to create, read, update, and delete browser cookies once jQuery and the plugin are loaded.
  • Set a cookie with $.cookie('name', 'value', { options }); supported options are expires (days until expiry; default is a session cookie), path (default is the current page), domain (applies to all subdomains), and secure (only sent over HTTPS).
  • Get a cookie's value with $.cookie('name').
  • Update a cookie by calling $.cookie('name', 'new value!') with the same name and a new value.
  • Delete a cookie with $.cookie('name', null), which removes the value and effectively deletes the entire cookie.
  • The author used this plugin to power smart email newsletter sign-up notifications on the Openview Labs website.

jQuery cookie makes it very easy to create, update and access information using cookies. I’ve used this plugin to handle smart email newsletter sign-up notifications on the Openview Labs website.

Download jQuery Plugin

The latest version of the Klaus Hartl’s jQuery cookie plugin is available for download on the Github. After you have loaded jQuery and the cookie plugin you can quickly get started working with cookies.

Working With Cookies

Set

Use the following JavaScript/jQuery syntax to create a cookie and store a value in it.

$.cookie(
    "name", 
    "value", 
    { 
        // The "expires" option defines how many days you want the cookie active. The default value is a session cookie, meaning the cookie will be deleted when the browser window is closed.
        expires: 7, 
        // The "path" option setting defines where in your site you want the cookie to be active. The default value is the page the cookie was defined on.
        path: '/', 
        // The "domain" option will allow this cookie to be used for a specific domain, including all subdomains (e.g. labs.openviewpartners.com). The default value is the domain of the page where the cookie was created.
        domain: 'openviewpartners.com', 
        // The "secure" option will make the cookie only be accessible through a secure connection (like https://)
        secure: true 
    }
);

Get

After you have stored information into your cookie, use this syntax to reference the value in your script.

$.cookie("name");

Update

If you want to change the information stored in a cookie, use this syntax to change the $.cookie value.

$.cookie("name", "new value!");

Delete

If you are done working with a cookie, it’s best to delete it. The following syntax will allow you to remove a value from a cookie, effectively deleting the entire cookie.

$.cookie("name", null);

If you have any questions, suggestions or rants don’t hesitate to blow up my spot in the comments below.

Resume