The jQuery cookie plugin 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.