Bubbling and capturing with addEventListener

8.4k views Asked by At

I recently discovered the difference between Bubbling and Capturing on DOM events, using javascript. Now I understand how it's supposed to work, but I've found a weird situation and I would like to know why is that happening.

According to Quirks mode, the event propagation starts with capturing on the outer div, reaches the bottom and then bubbles up to the top. The problem was when I started doing some tests.

On this first one, everything works as expected:

<div id="out">
    <div id="in">
        Click This!!
    </div>
</div>
<script type="text/javascript">
    document.getElementById('out').addEventListener('click', function(){
        alert('capture out');
    }, true);
    document.getElementById('in').addEventListener('click', function(){
        alert('capture in');
    }, true);
    document.getElementById('out').addEventListener('click', function(){
        alert('bubble out');
    }, false);
    document.getElementById('in').addEventListener('click', function(){
        alert('bubble in');
    }, false);
</script>

If you click the text, the alerts go 'capture out', 'capture in', 'bubble in' and 'bubble out'. The problem is using the following code:

<div id="out">
    <div id="in">
        Click This!!
    </div>
</div>
<script type="text/javascript">
    document.getElementById('out').addEventListener('click', function(){
        alert('bubble out');
    }, false);
    document.getElementById('in').addEventListener('click', function(){
        alert('bubble in');
    }, false);
    document.getElementById('out').addEventListener('click', function(){
        alert('capture out');
    }, true);
    document.getElementById('in').addEventListener('click', function(){
        alert('capture in');
    }, true);
</script>

In this case the alerts go 'capture out', 'bubble in', 'capture in' and 'bubble out'. If you notice, the only difference is that on the second one the bubbling is assigned first, but I don't think that should make any difference.

I've tried this with Firefox and Chrome, and the results are the same (I understand that internet explorer doesn't handle capturing).

1

There are 1 answers

2
Nickolay On BEST ANSWER

quirksmode simplified the model a little. Events in fact go through up to three phases: capturing, at target, and bubbling.

If you log the event.eventPhase like this:

document.getElementById('out').addEventListener('click', function(e){
    console.log(e.eventPhase + " : " + e.target.id + " : bubbling");
}, false);

... you'll see that the 'bubble in' and 'capture in' listeners fire during the AT_TARGET phase. Event listeners invoked for the same element during the same phase are invoked in the registration order.