Created
October 4, 2018 11:58
-
-
Save devarajchidambaram/51e878d1f0a959753da2c6461bfe1755 to your computer and use it in GitHub Desktop.
Event delegation in js
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
<!--- | |
Event delegation in JS | |
Ref | |
https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb | |
--> | |
<html> | |
<body> | |
<ul id="todo-app"> | |
<li class="item">Walk the dog</li> | |
<li class="item">Pay bills</li> | |
<li class="item">Make dinner</li> | |
<li class="item">Code for one hour</li> | |
</ul> | |
</body> | |
<script> | |
document.addEventListener('DOMContentLoaded', function () { | |
let app = document.getElementById('todo-app'); | |
// attach event listener to whole container | |
app.addEventListener('click', function (e) { | |
if (e.target && e.target.nodeName === 'LI') { | |
let item = e.target; | |
alert('you clicked on item: ' + item.innerHTML); | |
} | |
}); | |
}); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment