JavaScript Event : Part 1 – Bubbling and Capturing

Event Bubbling and Capturing

In computer science, Event means send a notification to subscribers once task is completed. So in JavaScript it could be user action such as mouse click, key pressed or it could be custom event. Howevent, not like other programing languages, JavaScript use fascinating mechanism to send and receive events in browser. I’m pretty sure, most of the developers use something like this

In DOM

<input value="Click me" onclick="alert('Click!')" type="button">

In JavaScript code

window.addEventListener('load', function(event) {
    console.log('page is fully loaded');
});

Since JavaScript is on Event driven programing language or built on Event Driven Architecture, Event plays major role in JavaScript Engine.

In JavaScript, there are two ways to propagate with event. Event Bubbling and Event Capturing.

Event Bubbling

When the event happen on element, first it run the handler on it then on its parent all the way up to root element on DOM. Event bubbling is default behaviour for most of the browsers.

<pre class="<style>
  form, div {
    margin: 10px;
    border: 1px solid blue;
  }
</style>

<form class="sample" onclick="alert('form')">FORM
  <div onclick="alert('div')">DIV
    <input type="button" value="Click Me" onclick="alert('p')"/>
  </div>
</form>
https://codepen.io/kamprasad2007/pen/povKepP

How do we stop event bubbling

Using stopPropagation()
It could be in DOM or in javascript function as below

<input value="Click me" onclick="event.stopPropagation()" type="button">

or

window.addEventListener('load', function(event) {
    console.log('page is fully loaded');
    event.stopPropagation();
});

Event Capturing

When event happen, that event start with root element on DOM and travel back to child which has attached with event handler. This mechanism is rarely use in code but sometime this can be useful.

<style>
  form, div {
    margin: 10px;
    border: 1px solid blue;
  }
</style>

<form>FORM
  <div>DIV
    <p><input type="button" value="Click Me"/></p>
  </div>
</form>

<script>
  for(let elem of document.querySelectorAll('*')) {
    elem.addEventListener("click", e => alert(`Capturing: ${elem.tagName}`), true);
  }
</script>

Overview


Useful links
https://en.wikipedia.org/wiki/Event_(computing)
https://en.wikipedia.org/wiki/Event-driven_programming

One Reply to “JavaScript Event : Part 1 – Bubbling and Capturing”

Leave a Reply