Saturday, November 2, 2024
Google search engine
HomeLanguagesJavascriptPhases of JavaScript Event

Phases of JavaScript Event

There are three different phases during the lifecycle of a JavaScript event.

  • Capturing Phase
  • Target Phase
  • Bubbling Phase

They follow the same order as listed above.

Capturing Phase is when the event goes down to the element. The target phase is when the event reaches the element and the Bubbling phase is when the event bubbles up from the element.

So among the three phases of an event, which phase uses the addEventListener(), and how the programmer can change it?

html




<body>
    <div class="container">
        <button id="btn">Click Me!</button>
    </div>
      
    <script type="text/javascript">
        document.getElementById('btn')
            .addEventListener('click', 
            function () {
                alert('Button Clicked!');
            })
    </script>
</body>


Output:

Phases of JavaScript Event

Phases of JavaScript Event

The addEventListener() method will be called during the Bubbling phase. The code shown above will use addEventListener() with two arguments. However, in the above code, .addEventListener() can be called with the third argument as “true” which will invoke the listener earlier during the capturing phase.

Example: This example shows the capturing phase.

html




<body id="bdy">
    <div id="container">
        <button id="btn">Click Me!</button>
    </div>
    <script type="text/javascript">
        document.getElementById('bdy')
            .addEventListener('click', function () {
            alert('Body!');
        })
        document.getElementById('container')
            .addEventListener('click', function () {
            alert('Div!');
        }, true)
        document.getElementById('btn')
            .addEventListener('click', function () {
            alert('Button!');
        })
    </script>
</body>


Output:  

Phases of JavaScript Event

Phases of JavaScript Event

In the above code, the body and button are in the bubbling phase (default) while the div is set to capturing phase. When a button is clicked it starts at the top again. When it comes to the body element, it does not run function because we are still in the capturing phase. But when it reaches div it runs the function because the third parameter of addEventListener() is “true”. So it has to run in the capturing phase. When it reaches the button it switches from the capturing phase to the target phase and lastly to the bubbling phase. It fires the addEventListener which is in default mode.

So the above code will give an alert msg box showing “div”, then “button” and lastly “body”.

RELATED ARTICLES

Most Popular

Recent Comments