user26732 user26732 - 16 days ago 9
Javascript Question

Unable to understand useCapture attribute in addEventListener

I have read article at https://developer.mozilla.org/en/DOM/element.addEventListener but unable to understand

useCapture
attribute. Definition there is:


If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture.


In this code parent event triggers before child,so I am not able to understand its
behavior.Document object has usecapture true and child div has usecapture set false and document usecapture is followed.So why document property is preferred over child.



function load() {
document.addEventListener("click", function() {
alert("parent event");
}, true);

document.getElementById("div1").addEventListener("click", function() {
alert("child event");
}, false);
}

<body onload="load()">
<div id="div1">click me</div>
</body>




Answer

Events can be activated at two occasions: At the beginning ("capture"), and at the end ("bubble"). Events are executed in the order of how they're defined. Say, you define 4 event listeners:

window.addEventListener("click", function(){alert(1)}, false);
window.addEventListener("click", function(){alert(2)}, true);
window.addEventListener("click", function(){alert(3)}, false);
window.addEventListener("click", function(){alert(4)}, true);

The alert boxes will pop up in this order:

  • 2 (defined first, using capture=true)
  • 4 (defined second using capture=true)
  • 1 (first defined event with capture=false)
  • 3 (second defined event with capture=false)