Skip to content

Instantly share code, notes, and snippets.

@flangofas
Created March 12, 2015 22:17
Show Gist options
  • Save flangofas/bf0dc1b9d297bba78e5e to your computer and use it in GitHub Desktop.
Save flangofas/bf0dc1b9d297bba78e5e to your computer and use it in GitHub Desktop.
Simple example of local storage - HTML5 API
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web Storage Example</title>
<meta charset="UTF-8" />
<script>
window.addEventListener('load', function(event) {
var key = document.getElementById('key');
var value = document.getElementById('value');
var add = document.getElementById('add');
var clear = document.getElementById('clear');
add.addEventListener('click', function(event) {
if (key.value !== "") {
console.log('key ' + key.value + ' value ' + value.value);
localStorage.setItem(key.value, value.value);
}
});
clear.addEventListener('click', function(event) {
localStorage.clear();
});
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
console.log('key is ' + key + ' and value is ' + localStorage.getItem(key));
}
});
window.addEventListener('storage', function(event) {
var k = event.key;
var newValue = event.newValue;
var oldValue = event.oldValue;
var url = event.url;
var storageArea = event.storageArea;
alert("EVENT:\n" + k + "\n" + newValue + "\n" + oldValue + "\n" + url + "\n" + storageArea);
});
</script>
</head>
<body>
Key: <input type="text" id="key" /><br />
Value: <input type="text" id="value" /><br />
<input type="button" id="add" value="Add to Storage" />&nbsp;
<input type="button" id="clear" value="clear" />&nbsp;
<span id="content"></span>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment