Categories
dom-events event-bubbling javascript

What is event bubbling and capturing?

1201

What is the difference between event bubbling and capturing? When should one use bubbling vs capturing?

3

  • 7

    I recommend this useful link: javascript.info/bubbling-and-capturing

    – MeirDayan

    Feb 20, 2020 at 11:15

  • @CommunityAns: this site is excellent, but this topic, particularly, is depicted in a somewhat confusing way.

    – Veverke

    Jun 22, 2020 at 8:38

  • Needing engineers to be aware of the difference of both, and have code that can be broken simply by choosing an “incorrect” propagation type, is in my opinion a code-smell (or anti-pattern). A better way to go about it is to just enforce a coding style where propagation type doesn’t matter.

    Jan 6 at 7:42

1691

+50

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

Capturing is also called “trickling”, which helps remember the propagation order:

trickle down, bubble up

Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

IE < 9 uses only event bubbling, whereas IE9+ and all major browsers support both. On the other hand, the performance of event bubbling may be slightly lower for complex DOMs.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true.

Example

<div>
    <ul>
        <li></li>
    </ul>
</div>

In the structure above, assume that a click event occurred in the li element.

In capturing model, the event will be handled by the div first (click event handlers in the div will fire first), then in the ul, then at the last in the target element, li.

In the bubbling model, the opposite will happen: the event will be first handled by the li, then by the ul, and at last by the div element.

For more information, see

In the example below, if you click on any of the highlighted elements, you can see that the capturing phase of the event propagation flow occurs first, followed by the bubbling phase.

var logElement = document.getElementById('log');

function log(msg) {
    logElement.innerHTML += ('<p>' + msg + '</p>');
}

function capture() {
    log('capture: ' + this.firstChild.nodeValue.trim());
}

function bubble() {
    log('bubble: ' + this.firstChild.nodeValue.trim());
}

function clearOutput() {
    logElement.innerHTML = "";
}

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('click', capture, true);
    divs[i].addEventListener('click', bubble, false);
}
var clearButton = document.getElementById('clear');
clearButton.addEventListener('click', clearOutput);
p {
    line-height: 0;
}

div {
    display:inline-block;
    padding: 5px;

    background: #fff;
    border: 1px solid #aaa;
    cursor: pointer;
}

div:hover {
    border: 1px solid #faa;
    background: #fdd;
}
<div>1
    <div>2
        <div>3
            <div>4
                <div>5</div>
            </div>
        </div>
    </div>
</div>
<button id="clear">clear output</button>
<section id="log"></section>

Another example at JSFiddle.

14

  • 45

    useCapture now supported in IE >= 9. source

    Aug 20, 2013 at 17:10


  • 8

    I know its too late to put comment but nice article i found here catcode.com/domcontent/events/capture.html

    – Just code

    Oct 18, 2013 at 9:56


  • 4

    Is triclkling the same as capturing? Crockford talks about Trickling v. Bubbling in this video talk – youtube.com/watch?v=Fv9qT9joc0M&list=PL7664379246A246CB around 1 hr 5 minutes.

    Jan 2, 2014 at 19:25

  • 12

    The answer above correct in regards to the order in the detailed explanation, but leaves you thinking that trickle occurs second with “bubble up, trickle down”. Events always go through the capture phase before the bubble phase. The correct order is trickle down => onElement => bubble up

    – runspired

    Dec 23, 2015 at 14:59


  • 2

    “With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.” — You should point out that not all events bubble (e.g., focus).

    – thdoan

    Jun 18, 2018 at 10:41

560

Description:

quirksmode.org has a nice description of this. In a nutshell (copied from quirksmode):

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.


What to use?

It depends on what you want to do. There is no better. The difference is the order of the execution of the event handlers. Most of the time it will be fine to fire event handlers in the bubbling phase but it can also be necessary to fire them earlier.

3

  • 1

    Does not both happens, first capturing and then bubbling, also what is dispatch event?

    Apr 6, 2018 at 4:31

  • 1

    a graphical example is here: javascript.info/bubbling-and-capturing

    – MeirDayan

    Feb 20, 2020 at 11:19

  • 1

    Capture phase handlers are particularly useful when some element’s code (code you don’t control, like a plugin) is stopping propagation, and you really want to know when that event occurs. You can pick it up on the way to them instead of on the way back. You might not get it in the bubbling phase if they stopped its propagation.

    – doug65536

    Nov 20, 2021 at 4:48


80

If there are two elements element 1 and element 2. Element 2 is inside element 1 and we attach an event handler with both the elements lets say onClick. Now when we click on element 2 then eventHandler for both the elements will be executed. Now here the question is in which order the event will execute. If the event attached with element 1 executes first it is called event capturing and if the event attached with element 2 executes first this is called event bubbling.
As per W3C the event will start in the capturing phase until it reaches the target comes back to the element and then it starts bubbling

The capturing and bubbling states are known by the useCapture parameter of addEventListener method

eventTarget.addEventListener(type,listener,[,useCapture]);

By Default useCapture is false. It means it is in the bubbling phase.

var div1 = document.querySelector("#div1");
var div2 = document.querySelector("#div2");

div1.addEventListener("click", function (event) {
  alert("you clicked on div 1");
}, true);

div2.addEventListener("click", function (event) {
  alert("you clicked on div 2");
}, false);
#div1{
  background-color:red;
  padding: 24px;
}

#div2{
  background-color:green;
}
<div id="div1">
  div 1
  <div id="div2">
    div 2
  </div>
</div>

Please try with changing true and false.

2