Event Propagation & Delegation

Event Propagation

[1]. Bubbling

[2]. Capturing

Syntax :

target.addEventListener(type, listener[, useCapture=false]);target.addEventListener("click", callOnClick);
DOM event flow

Not all events bubble

What do you think its going to happen when i click the box-3 ? Let’s check it out.

Event capturing sample
Event bubbling sample

Stop bubbling to outerMost

Event Delegation

How JavaScript Event Delegation Works

<ul id="parent-list">
<li id="post-1">Item 1</li>
<li id="post-2">Item 2</li>
<li id="post-3">Item 3</li>
<li id="post-4">Item 4</li>
<li id="post-5">Item 5</li>
<li id="post-6">Item 6</li>
// Get the element, add a click listener...document.getElementById("parent-list").addEventListener("click", function(e) {	// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID!
console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");



Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.