I am trying to understand the useCapture parameter in JavaScript addEventListener() . Here is my HTML:
<div id="wrapper"> <button id="button">Click me</button> </div>
Here is my javascript:
document.getElementById('wrapper').addEventListener('click', function () { console.log('Wrapper capture'); }, true); document.getElementById('wrapper').addEventListener('click', function () { console.log('Wrapper bubble'); }, false); document.getElementById('button').addEventListener('click', function () { console.log('Button bubble'); }, false); document.getElementById('button').addEventListener('click', function () { console.log('Button capture'); }, true);
Now I expected the order would be Wrapper capture, Button capture, Button bubble, Button bubble . Surprisingly, here is my result:
Wrapper capture Button bubble Button capture Wrapper bubble
Do two button handlers mix? I tested it in other browsers, but Chrome, Firefox and IE10 show the same behavior. I am a little puzzled by this. MDN , QuirksMode.org and the specification clearly describe the different phases and how the capture phase precedes the bubbling phase. Why does my little experiment cause the Button bubble handler to get called before my Button capture ?
Here is the scenario of what is happening: http://jsfiddle.net/Tr7G6/2
// Update It seems that the data binding order of the handlers.
document.getElementById('wrapper').addEventListener('click', function () { console.log('Wrapper capture'); }, true); document.getElementById('wrapper').addEventListener('click', function () { console.log('Wrapper bubble'); }, false); document.getElementById('button').addEventListener('click', function () { console.log('Button capture'); }, true); document.getElementById('button').addEventListener('click', function () { console.log('Button bubble'); }, false);
Binding to capture the first and second bubble makes the expected result, a cross browser. But this is stupid. Why does this order matter?