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:
- Capture Phase
- Target Phase
- 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!