Event bubbling vs event capturing in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Event Bubbling − Whenever an event happens on an element, the event handlers will first run on it and then on its parent and finally all the way up to its other ancestors.

Event Capturing − It is the reverse of the event bubbling and here the event starts from the parent element and then to its child element.

Following is the code for event bubbling vs event capturing in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .outer {
      display: inline-block;
      width: 400px;
      height: 200px;
      font-size: 20px;
      background-color: chartreuse;
   }
   .inner {
      width: 200px;
      height: 100px;
      font-size: 20px;
      background-color: blueviolet;
      text-align: center;
      margin: 20px;
   }
   .tags {
      display: inline-block;
      width: 400px;
      font-weight: bold;
      font-size: 18px;
   }
</style>
</head>
<body>
<h1>Event bubbling vs event capturing</h1>
<div class="outer">
OUTER
<div class="inner">INNER</div>
</div>
<div class="outer">
OUTER
<div class="inner">INNER</div>
</div>
<br />
<div class="tags">Bubbling</div>
<div class="tags">Capturing</div>
<div class="result"></div>
<script>
   let outerDiv = document.querySelectorAll(".outer");
   let innerDiv = document.querySelectorAll(".inner");
   let resEle = document.querySelector(".result");
   outerDiv[0].addEventListener("click", () => {
      resEle.innerHTML += "Outer div has been clicked" + "<br>";
   });
   innerDiv[0].addEventListener("click", () => {
      resEle.innerHTML = "";
      resEle.innerHTML += "Inner div has been clicked" + "<br>";
   });
   outerDiv[1].addEventListener("click",() => {
      resEle.innerHTML = "";
      resEle.innerHTML += "Outer div has been clicked" + "<br>";
   },true);
   innerDiv[1].addEventListener("click",() => {
      resEle.innerHTML += "Inner div has been clicked" + "<br>";
   }, true);
</script>
</body>
</html>

Output

On clicking the inner div having the event bubbling −

On clicking the inner div having the event capturing −


raja
Published on 17-Jul-2020 10:51:13
Advertisements