Created
May 1, 2019 03:41
-
-
Save joncancode/cc2a2d9c5b535ab6f8d354689b8b85fa 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> | |
<title>Event Delegation</title> | |
<style> | |
#completed-list-div { | |
display: none; | |
} | |
.complete-task { | |
color: blue; | |
cursor: pointer; | |
} | |
.completed { | |
text-decoration: line-through; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Hello <span id="name">World</span></h1> | |
<h2>Favorite Things</h2> | |
<ul id="fav-list"> | |
<li class="fav-thing">Dog bites</li> | |
<li class="fav-thing">Bee Stings</li> | |
<li class="fav-thing">Feeling Bad</li> | |
</ul> | |
<form> | |
<input id="new-thing" /> | |
<input id="new-thing-button" type="submit" value="Create new thing"></submit> | |
</form> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<script> | |
/* Independent Practice | |
Making a favorites list: event delegation | |
Refactor the code below. | |
The difference will be: use event delegation so that you only have | |
to set one event listener for all the items once, when the | |
code first runs, and you don't have to add any others whenever | |
someone adds an item. | |
Bonus: When the user mouses over each item, the item should turn grey. Don't use CSS hovering for this. | |
*/ | |
function addToList($list, thing) { | |
var $thingLi = $('<li>').html(thing); | |
addCompleteLink($thingLi); | |
$list.append($thingLi); | |
} | |
function addCompleteLink($li) { | |
var $completedLink = $('<span>').html(' complete task').addClass('complete-task'); | |
$li.append($completedLink); | |
$completedLink.on('click', function(event) { | |
$li.addClass('completed'); | |
$completedLink.html(''); | |
}); | |
} | |
$(document).ready(function() { | |
var $thingList = $('#fav-list'); | |
var $things = $('.fav-thing'); | |
var $button = $('#new-thing-button'); | |
var $newThingInput = $('#new-thing'); | |
$things.toArray().forEach(function(li) { | |
addCompleteLink($(li)); | |
}); | |
$button.on('click', function(event) { | |
event.preventDefault(); | |
var newThing = $newThingInput.val(); | |
if (newThing === '') { | |
alert('You must type in a value!'); | |
} else { | |
addToList($thingList, newThing); | |
$newThingInput.val(''); | |
} | |
}); | |
}); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment