I recently discovered the difference between Bubbling and Capturing on DOM events using javascript. Now I understand how this should work, but I found a strange situation, and I would like to know why this is happening.
In accordance with Quirks mode, the propagation of an event begins with a capture on the outer div, reaches the bottom and then bubbles up. The problem was that I started to run some tests.
In 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 on the text, the alerts will display “grab”, “grab”, “insert bubble” and “pop out”. The problem is this:
<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 warnings come out to “seize”, “entangle”, “seize” and “pop up”. If you notice, the only difference is that in the second case, the bubbles are assigned first, but I don't think that should matter.
I tried this with Firefox and Chrome, and the results are the same (I understand that Internet Explorer does not handle the capture).