What’s Cookie
A Cookie is a small amount of key value-based browser storage used to store tiny data on user’s browser by websites. It can be manipulated by JavaScript
Simple JavaScript code that manipulate cookie is
document.cookie = "key=value; expires=EXPIRY_TIME";
Cookie Plugins in jQuery
There are many jQuery plugins available to implement cookie easily with simple callbacks. That provides methods for add, remove or delete browser cookies.
List of Popular jQuery Cookies Plugins
- Carhartt’s jQuery cookie plugin – jquery.cookie.js – simple jQuery plugin for string and array-based cookie which also supports AMD, requirejs and commonjs.
- Google Code jQuery Plugin repository – jquery.cookies.js
Cookie manipulation with carhartl’s jQuery cookie Plugin
-
Create session cookie that expires after user exits browser.
Creating Cookie of string datatype
$.cookie('key','value');
Creating Cookie of array datatype
$.cookie('key',['value1','value2'])
Creating Cookie of json (object) datatype
$.cookie('key','{ "sub_key_1":"sub_value_1", "sub_key_2":"sub_value_2" }' );
-
Creating a cookie that expires after a specific time.
String cookie with 5 days of expiry
// this cookie expires after 5 days $.cookie('key','value',{expires: 5});
array cookie with 5 days of expiry
$.cookie('key',['value1','value2'], { expires: 5 });
object cookie with 5 days of expiry
$.cookie('key','{ "sub_key_1":"sub_value_1", "sub_key_2":"sub_value_2" }' , { expires: 5 } );
-
More options
How to set SSL (https) cookie with jQuery cookie plugin?
$.cookie('key','value' , { secure: true } );
How to set cross subdomain cookie with jQuery cookie plugin?
Just prexif your domain value with dot (i.e. “.yourdomain.com”) in cookie option
$.cookie('key','value' , { secure: true } );
So above cookie is valid for all subdomain of site vikaskbh.com Check demo here
Why & how to set cookie path with jQuery cookie plugin?
Path defines scope of cookie. By default, cookies are being set to directory structure of url. i.e. if you are accessing http://www.example.com/directory and try to set cookie, it will be set to /directory path. You could set it to root directory path “/” with cookie path option.
$.cookie('key','value' , { path: '/' } );
-
How to read cookie using jQuery plugin?
Reading cookie is simple, just pass cookie key to $.cookie() function.
Reading string cookie
$.cookie('key');
Reading array cookie
$.cookie('key').split(",");
Reading json cookie
$.parseJSON($.cookie('key'));
-
How to delete cookie using jQuery plugin?
To delete cookie, just use function $.removeCookie() and supply cookie key.
$.removeCookie('key');
Cookie manipulation with Google code cookie plugin
-
Create cookie
Simple string cookie
$.cookies.set('key');
JSON cookie
$.cookies.set('key',{ sub_key:'sub_value' });
-
Read cookie
$.cookies.get('key');
-
Delete cookie
$.cookies.del('key');