function CookieManager() {
this.cookies = new Array();
};
CookieManager.prototype.setCookie = function(name, data) {
var expires = "";
var jsonData = JSON.stringify(data);
document.cookie = name + "=" + jsonData + "; " + expires + "; path=/";
if (this.cookies.indexOf(name) < 0) {
this.cookies.push(name);
}
};
CookieManager.prototype.readCookie = function(name) {
if(name === undefined && this.cookies.length > 0){
name = this.cookies[0];
}
if(jQuery.isNumeric(name)){
if(this.cookies.length - 1 >= name){
name = this.cookies[name];
}
}
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return JSON.parse(c.substring(nameEQ.length, c.length));
}
return null;
};
CookieManager.prototype.emptyCookie = function(name) {
this.setCookie(name, null);
var ix = this.cookies.indexOf(name);
this.cookies.splice(ix, 1);
};
// Wire up to jquery
jQuery.CookieManager = new CookieManager();
//EXAMPLE USAGE
//=============
// store array in cookie
var myData = ['id1', 'id2', 'id3'];
var myOtherData = { stuff: "data" };
$.CookieManager.setCookie('test', myData);
$.CookieManager.setCookie('test2', myOtherData);
// read data from cookie
console.log($.CookieManager.readCookie('test2'));
// read data from first cookie
console.log($.CookieManager.readCookie());
// read data from cookie based on insert index
console.log($.CookieManager.readCookie(1));
// list of known cookies kept
$.CookieManager.cookies.forEach(function(element){
console.log(element);
});
// clear out data and remove from cookies list
$.CookieManager.emptyCookie('test');
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.