If jQuery is your javascript manipulation library of choice, then you would be pretty pleased that developer Klaus Hartl took the time and whipped up his excellent jquery-cookie plugin, thereby making the act of setting or retrieving browser cookies in your jQuery JavaScript a snap!
To set the value of a cookie is pretty simple, just pass along a key and a value, and as expected, you can make it a little more verbose by including a selection of all the standard cookie stuff like expiry date, path, or domain.
In action:
$.cookie("mycookie", "on!"); //Additionally, to set a timeout of a certain number of days (10 here) on the cookie: $.cookie("mycookie", "on!", { expires : 10 });
Note, if the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.
This snippet covers most of the options in setting up a cookie that are available to you:
$.cookie("mycookie", "on!", { expires : 10, //expires in 10 days path : '/', //The value of the path attribute of the cookie //(default: path of page that created the cookie). domain : 'jquery.com', //The value of the domain attribute of the cookie //(default: domain of page that created the cookie). secure : true //If set to true the secure attribute of the cookie //will be set and the cookie transmission will //require a secure protocol (defaults to false). });
To read back the value of the cookie:
var cookieValue = $.cookie("mycookie"); //You may wish to specify the path parameter if the cookie was created on a different path to the current one: var cookieValue = $.cookie("mycookie", { path: '/view' });
To delete a cookie:
$.removeCookie("mycookie");
Right, that should now be enough to get you up and running!
Related Link: https://github.com/carhartl/jquery-cookie