Bubbling and capturing

  1. Bubbling
    1. this and event.target
    2. Stopping the bubbling
  2. Capturing
  3. Summary

DOM elements can be nested inside each other. And somehow, the handler of the parent works even if you click on it’s child.

The reason is event bubbling.

For example, the following DIV handler runs even if you click a nested tag like EM or CODE:

<div onclick="alert('Div handler worked!')">
  <em>Click here triggers on nested <code>EM</code>, not on <code>DIV</code></em>
</div>

That’s because an event bubbles from the nested tag up and triggers the parent.

Bubbling

The main principle of bubbling states:
After an event triggers on the deepest possible element, it then triggers on parents in nesting order.

For example, there are 3 nested divs:

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">

<div class="d1">1  <!-- the topmost -->
    <div class="d2">2
        <div class="d3">3 <!-- the innermost -->
        </div> 
    </div>
</div>

</body>
</html>

The bubbling guarantees that click on Div 3 will trigger onclick first on the innermost element 3 (also caled the target), then on the element 2, and the last will be element 1.

Bubbling events order

The order is called a bubbling order, because an event bubbles from the innermost element up through parents, like a bubble of air in the water.

Click below to see it bubble:

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">

<div class="d1" onclick="highlight(this)">1  
    <div class="d2" onclick="highlight(this)">2
        <div class="d3" onclick="highlight(this)">3 
        </div> 
    </div>
</div>

<script>
function highlight(elem) {
    elem.style.backgroundColor='yellow'
    alert(elem.className)
    elem.style.backgroundColor = ''
}
</script>

</body>
</html>
Open the code in new window

this and event.target

The deepest element which triggered the event is called the target or, the originating element.

Internet Explorer has the srcElement property for it, all W3C-compliant browsers use event.target. The cross-browser code is usually like this:

var target = event.target || event.srcElement

When handlers trigger on parents:

  • event.target/srcElement - remains the same originating element.
  • this - is the current element, the one event has bubbled to, the one which runs the handler.

Bubbling events order

In the example below, each DIV has an onclick handler which outputs both target and this.

Click on a div.

Note that:

  • the target is constant through all bubbling process,
  • this changes and gets highlighted.

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">

<div class="d1">1  
    <div class="d2">2
        <div class="d3">3 
        </div> 
    </div>
</div>

<script>
var divs = document.getElementsByTagName('div')

for(var i=0; i<divs.length; i++) {
  divs[i].onclick = function(e) {
    e = e || event
    var target = e.target || e.srcElement

    this.style.backgroundColor='yellow'
    
    alert("target = "+target.className+", this="+this.className)

    this.style.backgroundColor = ''
  }
}
</script>

</body>
</html>
Open the code in new window

In W3C-compliant browsers this is also available as event.currentTarget.

attachEvent does not pass this or event.currentTarget at all.

Stopping the bubbling

The bubbling goes right to the top. When an event occurs on an element - it will bubble up to <HTML>, triggering handlers on it’s way.

But a handler may decide that event is fully processed and stop the bubbling.

The code is:

  • For W3C-compliant browsers:
    event.stopPropagation()
    
  • For IE<9:
    event.cancelBubble = true
    

The cross-browser-code:

element.onclick = function(event) {
    event = event || window.event // cross-browser event
    
    if (event.stopPropagation) {
        // W3C standard variant
        event.stopPropagation()
    } else {
        // IE variant
        event.cancelBubble = true
    }
}

There is a one-lined variant too:

event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true)

If the element has several handlers on same event, then handlers are independent. All of them get executed..

For example, if there are two onclick handlers on the same link, then stopping bubbling in one of them has no effect on the other one. Also, the browser doesn’t guarantee the order in which they trigger.

Capturing

In all browsers, except IE<9, there are two stages of event processing.

The event first goes down - that’s called capturing, and then bubbles up. This behavior is standartized in W3C specification.

W3C events order

According to this model, the event:

  1. Captures down - through 1 -> 2 -> 3.
  2. Bubbles up - through 3 -> 2 -> 1.

All methods of event handling ignore the caputiring phase. Using addEventListener with last argument true is only the way to catch the event at capturing.

elem.addEventListener( type, handler, *!*phase*/!* )

phase = true
The handler is set on the capturing phase.
phase = false
The handler is set on the bubbling phase.

Click in a div below to see capturing in action (no IE<9):

It should be 1 -> 2 -> 3.

Source JavaScript of the example:

var divs = document.getElementsByTagName('div')

for(var i=0; i<divs.length; i++) {
  divs[i].addEventListener("click", highlightThis, true)
}

Click to open in the playground: tutorial/browser/events/bubbling/capture/index.html.

In real-life the capturing phase is rarely used. But..
There are events which don’t bubble, but can be captured. For example, onfocus/onblur.

Now let’s assign handlers at both stages.

Click on a div below to see the event processing order (no IE<9):

It should be 1 -> 2 -> 3 -> 3 -> 2 -> 1.

Source JavaScript of the example:

var divs = document.getElementsByTagName('div')

for(var i=0; i<divs.length; i++) {
  divs[i].addEventListener("click", highlightThis, true)
  divs[i].addEventListener("click", highlightThis, false)
}

Click to open in the playground: tutorial/browser/events/bubbling/both/index.html.

Summary

  • Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
  • All handlers work on bubbling stage excepts addEventListener with last argument true, which is the only way to catch the event on capturing stage.
  • Bubbling/capturing can be stopped by event.cancelBubble=true (IE) or event.stopPropagation() for other browsers.

Tutorial

Donate

Donate to this project