Categories: JavaScriptjQuery

jQuery: Setting cookies

Setting and clearing cookies with jQuery is really easy but it’s not included in the jQuery core and requires a plug-in. This post shows how to set, get the value of and clear cookies with jQuery.

The plugin

Download the jQuery cookie plugin here: https://plugins.jquery.com/cookie/
Note that I am not the author of this plugin.

Setting a cookie with jQuery is as simple as this, where a cookie is created called “mycookie” with a value of “100”:

$.cookie(“mycookie”, “100”);

 

This is a session cookie which is set for the current path level and will be destroyed when the user exits the browser. To make the same cookie last for e.g. 10 days do this:

$.cookie(“mycookie”, “100”, { expires: 10 });

 

Note: the above examples will apply the cookie to the current path level.

If the page requested is http://www.example.com/file.html then it will be set for the / path and will be available for all paths at the domain. If the page is http://www.example.com/subpath/file.html then it will be set for the /subpath level and will not be accessible at / (or /otherpath etc).

To explicitly make the cookie available for all paths on your domain, make sure the path is set:

$.cookie(“mycookie”, “100”, { path: ‘/’ });

 

To limit it to a specific path instead:

$.cookie(“mycookie”, “100”, { path: ‘/admin’ });

 

Get the cookie’s value

Getting the cookie’s value is also very easy with jQuery. The following would show the value of the “example” cookie in a dialog window:

alert( $.cookie(“mycookie”) );

 

And finally, to delete a cookie set the value to null. Setting it to e.g. an empty string doesn’t remove it; it just clears the value.

$.cookie(“mycookie”, null);

 

SGH

At the same time, I can’t think of anything more satisfying than sitting in front of TV, eating take-away, lights down low, in my pyjamas and watching crap on TV. Basically, I strive to live a balanced life. Fun. Serious. Fast. Slow. Brainy. Bimbotic. Intense. Lazy. You get the drift.

Recent Posts

Free GG Mug Mockup

GG Mug Mockup designed for logo branding of companies and brands.

6 years ago

Lovtony Font Duo – Modern Sans Serif

A great font/script for creating beautiful logos, posters, wedding invitations, blog posts, social media, and…

6 years ago

Free Men T-Shirt Mockup

Realistic T-Shirt Mockup PSD which you can use freely to showcase your apparel design.

6 years ago

Classic Coffee Mug Mock-up Free PSD

Classic coffee mug Mock-up Free PSD. Free mug mockup PSD to showcase your branding design…

6 years ago

Juliette – Stylish Handwritten Signature Font

Juliette - Stylish Handwritten Signature Font

6 years ago

XXII Aven Sans Serif Font Family

XXII Aven Font Family - a new modern all-caps sans serif font with versatility in creativity.

6 years ago