Created
May 13, 2016 16:55
-
-
Save queerviolet/5889997e8cfc8fd1063ad48ca1f10fa1 to your computer and use it in GitHub Desktop.
Todo list jquery example
This file contains hidden or 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> | |
<link rel=stylesheet href=style.css> | |
</head> | |
<body> | |
<h1 id=header>trip planner</h1> | |
<ul class=todo-list> | |
<li class=todo-list-new-item> | |
<form class=todo-list-new-item-form> | |
<input name=todo type=text placeholder='Add a new item'> | |
<input type=submit value=add> | |
</form> | |
</ul> | |
</body> | |
<!-- jQuery being loaded off a CDN --> | |
<script src="https://code.jquery.com/jquery-2.2.3.js" | |
integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" | |
crossorigin="anonymous"></script> | |
<!-- the JS to run the todo list --> | |
<script src=todo-list.js></script> | |
</html> |
This file contains hidden or 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
"use strict"; | |
var todos = [ | |
'drink lots of water', | |
'remember your headlamp', | |
'take deep breaths', | |
] | |
var newItem = $('.todo-list-new-item') | |
function addTodo(todo) { | |
var li = $(`<li class=todo>${todo}</li>`) | |
// You can attach event listeners every time you create a new element: | |
// li.on('click', function(event) { this.classList.toggle('done') }) | |
// | |
// BUT: If you have multiple ways of attaching elements, and you forget, | |
// some of your stuff won't work. | |
// BUT: This might create a lot of event listeners. | |
newItem.before(li) | |
} | |
// 1. Put this stuff on the page | |
todos.forEach(function(todo) { | |
console.log(todo) | |
var li = document.createElement('li') | |
li.textContent = todo | |
addTodo(todo) | |
}); | |
$('.todo-list-new-item-form').on('submit', function(event) { | |
addTodo(this.todo.value) | |
this.todo.value = '' | |
event.preventDefault(); // Stop the form from actually submitting. | |
}) | |
// Attach a click listener to the list, rather than each item, | |
// then use jQuery's event delegation feature to filter only clicks on | |
// elements matching li.todo | |
// | |
// https://learn.jquery.com/events/event-delegation/ | |
$('ul').on('click', 'li.todo', function(event) { | |
$(this).toggleClass('done') | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment