Event Bubbling
While developing a webpage or a website via JavaScript, the concept of
event bubbling is used where the event handlers are invoked when one
element is nested on to the other element and are part of the same event.
This technique or method is known as Event Bubbling.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Event Bubbling</title>
</head>
<body>
<div id="p1">
<button id="c1">I am child button</button>
</div>
<script>
var parent = document.querySelector('#p1');
parent.addEventListener('click', function(){
console.log("Parent is invoked");
});
var child = document.querySelector('#c1');
child.addEventListener('click', function(){
console.log("Child is invoked");
});
</script>
</body>
</html>
Stopping Bubbling
Beginning from the target and moving towards the top is the bubbling i.e.
starting from the child to its parent, it moves straight upwards. But a handler
can also take decision to stop the bubbling when the event has been
processed completely. In JavaScript, we use the event.stopPropagation
() method.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Event Bubbling</title>
</head>
<body>
<div id="p1">
<button id="c1" onclick="event.stopPropagation()">I am child</button>
</div>
<script>
var parent = document.querySelector('#p1');
parent.addEventListener('click', function(){
console.log("Parent is invoked");
});
var child = document.querySelector('#c1');
child.addEventListener('click', function(){
console.log("Child is invoked");
});
</script>
</body>
</html>
Event Capturing
Netscape Browser was the first to introduce the concept of Event Capturing.
Event Capturing is opposite to event bubbling, where in event capturing, an
event moves from the outermost element to the target.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Event Capturing</title>
</head>
<body>
<div id="p1">
<button id="c1">I am Child</button>
</div>
<script>
var parent = document.querySelector('#p1');
var child = document.querySelector('#c1');
parent.addEventListener('click', function(){
console.log("Parent is invoked");
},true);
child.addEventListener('click', function(){
console.log("Child is invoked");
});
</script>
</body>
</html>