Skip to content

Instantly share code, notes, and snippets.

@AdamGerthel
Last active April 15, 2017 21:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save AdamGerthel/9409656 to your computer and use it in GitHub Desktop.
Save AdamGerthel/9409656 to your computer and use it in GitHub Desktop.
Local Storage example
<!doctype html>
<html>
<head>
<title>Local Storage Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<style>
body {
font-family: arial;
}
</style>
</head>
<body>
<h1>Local Storage</h1>
<div class="form">
<input type="text" placeholder="To do" class="todo"/>
<button>Store</button>
</div>
<ul>
</ul>
<script type="text/javascript">
$(document).ready(function() {
// Build our todo list
var buildTodoList = function(data) {
$('ul').find('li').remove();
for(i = 0; i < data.length; i++) {
$('ul').append('<li>' + data[i] + '</li>');
}
};
// Define the array where we store todos
if (localStorage["todos"]) {
var todos = JSON.parse(localStorage["todos"]);
buildTodoList(todos);
} else {
var todos = []
};
// Handle new todos
$('.form button').click(function() {
// Get the value from the input field
var value = $(this).parent('.form').find('input').val();
todos.push(value)
localStorage["todos"] = JSON.stringify(todos);
buildTodoList(todos);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment