Skip to content

Instantly share code, notes, and snippets.

@Cifro
Created August 31, 2011 17:52
Show Gist options
  • Save Cifro/1184183 to your computer and use it in GitHub Desktop.
Save Cifro/1184183 to your computer and use it in GitHub Desktop.
JavaScript cookies on steroids

Using

Saves all in one coockie file as JSON string. Needs native JSON support in browsers or json2.js

Cookies.cookiePlugin = $.cookie // or jQuery.cookie for no conflict or whatever...
Cookies.cookieName = 'myCookie';
Cookies.jquery = $ // or jQuery
Cookies.path = '/path/';

Cookies.set('someColor', '#f00');

Cookies.get('someColor'); // #f00

options = Cookies.load();

options.someColor; // #f00

options.someColor = '#0f0';

Cookies.save(options);

Dependences

/**
* Cookies on steroids
* https://gist.github.com/1184183
*
* Copyright (c) 2011 Cifro Nix (about.me/Cifro)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
var Cookies = {
cookieName: 'cookiesOnSteroids',
jquery: {},
cookiePlugin: {},
path: '/',
data: {},
get: function(key){
return this.load(key);
},
set: function(key, value){
this.data[key] = value;
this.save();
return value;
},
reset: function(){
this.data = {};
this.cookiePlugin(this.cookieName, null, {path: this.path});
},
load: function(key){
var data = JSON.parse(this.cookiePlugin(this.cookieName));
if(data == null){
return null;
}
this.data = data;
if(key == undefined){
return this.data;
}else{
if(this.data[key] != undefined)
return this.data[key];
else
return null;
}
},
save: function(data){
if(data != undefined){
this.data = this.jquery.extend(this.data, data);
}
var opt = {path: this.path};
var temp = JSON.parse(this.cookiePlugin(this.cookieName));
if(temp == null){
this.cookiePlugin(this.cookieName, JSON.stringify(this.data), opt);
}else{
var mergedData = this.jquery.extend(temp, this.data);
this.cookiePlugin(this.cookieName, JSON.stringify(mergedData), opt);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment