Bubbling and capture with addEventListener

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).

+6
source share
1 answer

quirksmode simplified the model a bit. Events actually go through up to three stages: capture, target and sparging .

If you register event.eventPhase as follows:

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

... you will see that during the AT_TARGET phase, the “bubble inside” and “capture” listeners light up. Event listeners called for the same element during the same phase are called in registration order.

+9
source

Source: https://habr.com/ru/post/907098/


All Articles