Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Created October 16, 2012 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save netsi1964/3897580 to your computer and use it in GitHub Desktop.
Save netsi1964/3897580 to your computer and use it in GitHub Desktop.
javascript localstorage toDo list
/****
Sten Hougaard, @netsi1964, Localstorage items
Ver 0.98, not fully tested
Please note: Do not support storing of objects with functions
Added option to parse key (when using more than one localstorage)
Changed names from toDos to items, more generic
****/
var items;
if (typeof localStorage === 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
items = {
key: 'items'+(new Date()-new Date(1964,8,23)),
getItems: function(key) {
key = (typeof key!=='undefined') ? key : this.key;
var _temp = localStorage.getItem(key);
var current = (_temp===null) ? [] : JSON.parse(_temp);
localStorage.setItem(key, JSON.stringify(current));
return current;
},
add: function(oItem, key) {
key = (typeof key!=='undefined') ? key : this.key;
var items = this.getItems(key);
items[items.length] = JSON.stringify(oItem);
return localStorage.setItem(key, JSON.stringify(items));
},
set: function(index, value, key) {
key = (typeof key!=='undefined') ? key : this.key;
var items = JSON.parse(this.getItems());
items[index] = value;
localStorage.setItem(key, JSON.stringify(items));
return items;
},
get: function(index, key) {
key = (typeof key!=='undefined') ? key : this.key;
var items = this.getItems();
return JSON.parse(items[index]);
},
remove: function(index, key) {
key = (typeof key!=='undefined') ? key : this.key;
var items = this.getItems();
var removed = items.splice(index, 1);
localStorage.setItem(key, JSON.stringify(items));
return removed;
}
}
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!'); //data wasn’t successfully saved due to quota exceed so throw an error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment