Table of contents
1.
Introduction
2.
Understanding the JavaScript Events
2.1.
Event Handlers and Event Listeners
2.2.
Event Flow
3.
Three Phases of Event Flow
3.1.
1. Capture Phase
3.1.1.
Implementation
3.1.2.
Output
3.2.
2. Target Phase
3.3.
3. Bubble Phase
3.3.1.
Implementation
3.3.2.
Output
4.
Frequently Asked Questions
4.1.
What are the benefits of JavaScript event handlers?
4.2.
In JavaScript, what is the difference between bubbling and capturing?
4.3.
What's the best way to avoid capturing an event?
4.4.
What is event-triggered control, and how does it work?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Phases of JS Event

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Are you familiar with JavaScript Events? A JavaScript event is any action that takes place when we interact with a website. These actions can be clicking a link or button, entering text into an input box or text area, pressing a key on the keyboard, making a selection in a select box, submitting a form, moving the mouse pointer, and so on. In some circumstances, such as page load and unload events, the browser itself might trigger the events.

In this article, we will learn the different phases of a JavaScript event that occur during the lifecycle of an event. To have a better grasp of the various phases, we shall use a few examples and see how they are implemented on web pages.

I hope you will enjoy learning more about javascript event phases.

Also Read, Javascript hasOwnProperty

Understanding the JavaScript Events

Events are actions that occur in the browser and can be started by the user or by the browser itself. A few instances of common events that can occur on a website are as follows:

  • When the page loads completely.
  • When the user presses a button.
  • The user fills out a form and submits it.
  • A key is pressed on the keyboard by the user.

Event Handlers and Event Listeners

An event is triggered when a user clicks a button or presses a key. These are referred to as a click or keypress event, respectively. An event handler is a JavaScript function that runs when an event occurs. An event listener adds a responsive interface to an element, allowing the element to wait and "listen" for the event to occur.

When it comes to assigning events to elements, there are three options:

  • Handlers for inline events
  • Properties of event handlers
  • Event listeners

Let's have a look at a simple example: an event listener handles events that are fired by a single element; here is the button:

Event Flow

In the above section, we saw the basic concept of javascript events. Now, let’s see the browser's stages of handling events targeted at nested elements. The sequence in which events are received on a web page is known as the event flow. 

Let’s understand it more clearly with an example. Suppose you click on an element nested to other elements, such as a div or a button. Before you click on the target element, it must initially trigger the click event on each parent element, starting with the global window object at the top. In general, every HTML element is a child of the window object.

Three Phases of Event Flow

We become confused about which event handler will trigger first if we have numerous nested items handling the same event. In such situations, knowing the sequence of events comes in handy.

During the lifecycle of a JavaScript event, there are three distinct phases:

  1. Capture Phase
  2. Target Phase
  3. Bubbling Phase

The diagram below will help you better comprehend the event propagation life cycle.

( Document Object Model Event Flow, Source: blog.bitsrc.io )

1. Capture Phase

In the event capturing phase, an event originates at the least particular element and progresses downhill to the most specific element. 

During the capture process:

  • The browser will execute if the element's outermost ancestor <html> has a click event handler registered for the capturing phase.
  • Then it moves on to the next element inside html> and repeats the process, continuing until it reaches the immediate parent of the element that was actually selected.

Implementation

<!--- HTML Code--->
<html>
  <head>
    <title>Event Capture Demo</title>
  </head>
  <body>
    <h1>Event Capture Demo</h1>
    <article id="main">
      <div id="parent" style="border: 2px solid brown; margin: 10px;">
        <div id="child" style="border: 2px dashed green; margin: 10px;">
          <p>This is a paragraph.</p>
        </div>
    </article>
  </body>
</html>

<!--- event capture --->
<script type="text/javascript">
  var ancestor = document.getElementById("main");
  var parent = document.getElementById("parent");
  var child = document.getElementById("child");
  ancestor.addEventListener("click", function(event){
    console.log("main clicked");
  });
  parent.addEventListener("click", function(event){
    console.log("parent clicked");
  });
  child.addEventListener("click", function(event){
    console.log("child clicked");
  });
</script>

Output

In the above example, the click event handlers of all parent elements are called when you click on the ‘P’ element, starting with the outermost and propagating inside the target element ‘P’: HTML->BODY->ARTICLE->DIV->P.

2. Target Phase

A target element is the most deeply nested element that generated the event. It can be accessed as “event.target”. The target element, or the element that triggered the event, receives the event.

During the target phase:

  • If the target property has an event handler for the click event registered on it, the browser will execute it.
  • If bubbles are true, the event is propagated to the selected element's direct parent, then the next, until it reaches the <html> element. If bubbles are false, the event is not propagated to any of the target's ancestors. (Note: Don’t worry about the keyword “bubble phase”, we will discuss it in detail in the next section.)

3. Bubble Phase

The bubble phase is the opposite of capturing. In the event bubbling model, an event starts at the most specific element and then flows upward to the least specific element (the document or even window).

The exact opposite of the capturing phase occurs during the bubbling phase:

  • The browser will execute if the direct parent of the element selected has a click event handler registered for the bubbling phase.
  • Then it repeats the process for the next immediate ancestor element, then the next, and so on until it reaches the <html> element.

Implementation

<!--- Event bubbling--->
<html>
<head>
<title>Event Bubbling</title>
</head>
<body onclick="console.log('The body handler is here!');">
<h1>Event Bubbling</h1>
<article style="border: 10px solid red; margin: 10px;" id="ancestor" onclick="console.log('ARTICLE handler'); event.stopPropagation()">
    This is the article element.
    <div style="border: 10px solid blue; margin: 10px;" id="parent" onclick="console.log('DIV handler')">
        This is the div element.
        <p style="border: 10px solid green; margin: 10px;" id="child" onclick="console.log('P handler')">
            This is the paragraph.
        </p>
    </div>
</article>
</body>
</html>

Output

In the above example, the click event handlers of all parent elements are called when you click on the ‘P’ element, starting with the outermost and propagating inside to the target element ‘P’. The flow is as follows: P->DIV->ARTICLE->BODY->HTML.

Practice it on an online javascript editor.

Also check out - Phases of Compiler

Frequently Asked Questions

What are the benefits of JavaScript event handlers?

User input, user actions, and browser activities can all be handled and verified by event handlers: Things to do every time page loads. After the page has been closed, a few things need to be done. When a user clicks a button, an action should be executed.
 

In JavaScript, what is the difference between bubbling and capturing?

The event is initially captured and handled by the innermost element via bubbling and then propagated to the outermost elements. The event is first collected by the outermost element and then transmitted to the inner elements with capturing.

 

What's the best way to avoid capturing an event?

If you add a listener to the capturing phase rather than the bubbling phase, you can use the same technique to stop the event from propagating down to child elements: event.stopPropagation(). This post has been active. The function addEventListener() should receive false as the third argument.

 

What is event-triggered control, and how does it work?

The goal of event-triggered control is to reduce the amount of communication in networked control systems. This means that output or actuator signals are only sent over the network if an event-triggering condition is broken to ensure a specific level of control performance.

Conclusion

In this article, we learned event bubbling and capturing in JavaScript can effectively handle events within web applications. Understanding the event flow and how capturing and bubbling work will help you optimise your web application's event handling. 

We hope that this blog has helped you learn more about Javascript Phases, and if you want to learn more, check out our other posts on ‘Javascript BOM’ and ‘JavaScript DOM.’ Please upvote our blog to assist other ninjas in growing.

Check out this problem - Smallest Distinct Window.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass