Skip to content

Instantly share code, notes, and snippets.

@kn9ts
Created May 13, 2015 08:25
Show Gist options
  • Save kn9ts/015ea62d91449c334b60 to your computer and use it in GitHub Desktop.
Save kn9ts/015ea62d91449c334b60 to your computer and use it in GitHub Desktop.
Simple local storage function to store data in local storage and cookies if jquery plugin is existent
/**
* LOCAL STORAGE MANAGEMENT FUNCTION
* @param options - local(bool), content(object), backup(bool)
* @param key
* STORE CONTENT locally or in cookie or BOTH
*
* HOW TO USE:
localStorage('key') //Returns the content if existing, or false if it doesnt
localStorage('key', {
content: the content, can be a raw object, string or raw array //it is stringified by the function
local: true/false //yes or no if you want to store only in localStorage
})
*/
var localStorage = function(key, options) {
if (options) { //store this data
if (!options.local) {
localStorage.setItem(key, JSON.stringify(options.content));
} else { //also in cookie too
if ($.cookie) $.cookie(key, options.content);
localStorage.setItem(key, JSON.stringify(options.content));
}
} else if (options === false) { //if options == false
localStorage.removeItem(key);
if ($.cookie) $.cookie(key, false); //remove everything
}
//if only one argument is given retrieve that data from localstorage
return arguments.length == 1 ? JSON.parse(localStorage.getItem(key)) : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment