Skip to content

Instantly share code, notes, and snippets.

@devarajchidambaram
Created October 4, 2018 11:58
Show Gist options
  • Save devarajchidambaram/51e878d1f0a959753da2c6461bfe1755 to your computer and use it in GitHub Desktop.
Save devarajchidambaram/51e878d1f0a959753da2c6461bfe1755 to your computer and use it in GitHub Desktop.
Event delegation in js
<!---
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