Created
April 27, 2016 00:43
-
-
Save broofa/1c6e9c0fa86fdd4e4a3da08d12562672 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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