HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

What is event bubbling and capturing?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
eventandcapturingbubblingwhat

Problem

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

Solution

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

  • addEventListener on MDN



  • Events Advanced on QuirksMode



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 += ('
' + msg + '');
}

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
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;
}
1
2
3
4
5




clear output
`



Another example at JSFiddle.

Code Snippets

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

Context

Stack Overflow Q#4616694, score: 1765

Revisions (0)

No revisions yet.