Skip to content

Instantly share code, notes, and snippets.

@broofa
Created April 27, 2016 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save broofa/1c6e9c0fa86fdd4e4a3da08d12562672 to your computer and use it in GitHub Desktop.
Save broofa/1c6e9c0fa86fdd4e4a3da08d12562672 to your computer and use it in GitHub Desktop.
<!DOCTYPE html />
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script>
// Array of items to display
var items = [];
// (Re)render the list of items
function renderList() {
$('ul').empty();
items.forEach(function(item) {
$('ul').append('<li>' + item + '</li>');
});
}
// Once document has finished loading ...
$(document).ready(function() {
// Get any previously stored items in LocalStorage
items = localStorage.getItem('items');
// If we found some ...
if (items) {
// parse the JSON string -> array and re-render
items = JSON.parse(items);
renderList();
}
// When the button is clicked ...
$('button').on('click', function() {
// Get text from input field and add it to items[]
var title = $('input')[0].value;
items.push(title);
// Save in local storage (as JSON string)
window.localStorage.setItem('items', JSON.stringify(items));
// Re-render
renderList();
});
});
</script>
</head>
<body>
<input type="text" /><button>Add</button>
<ul>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment