As I understand it, the DOM Level 2 event handling works in the following order:
- capturing from the top HTML element all the way to before target
- the target itself
- bubbling all the way back the top HTML element
example is at: https://jsfiddle.net/uwe5dmxw/
(I will include the code at the end of this question)
But if I click on the "child" element (the lowest level descendent) on the current Google Chrome, Firefox, Safari, and even on IE 11, I get consistent result in this order:
- HTML capturing
- BODY capturing
- Parent capturing
- target bubbling
- target capturing
- Parent bubbling
- BODY bubbling
- HTML bubbling
That is, the order of the "target capturing" and "target bubbling" is reversed.
As I understood it, although the DOM Level 2 said event reaches target only once, but most browsers implement it as reaching it twice, once during event capturing and once during event bubbling. But the fact is, why is "target capturing" and "target bubbling" reversed?
Code: (but just a demo, you don't need to look at it if not necessary)
<div id="hi">
hello
<div id="child">
child
</div>
</div>
JavaScript:
var parentElement = document.getElementById("hi"),
childElement = document.getElementById("child"),
htmlElement = document.getElementsByTagName("html")[0],
bodyElement = document.getElementsByTagName("body")[0];
// ------------------ Bubble --------------------
htmlElement.addEventListener("click", function() {
console.log("<html> clicked " + new Date().getTime(), this);
});
bodyElement.addEventListener("click", function() {
console.log("<body> clicked " + new Date().getTime(), this);
});
parentElement.addEventListener("click", function() {
console.log("Parent clicked " + new Date().getTime(), this);
});
childElement.addEventListener("click", function() {
console.log("Child clicked at " + new Date().getTime(), this);
});
// ------------------ Use Capture --------------------
htmlElement.addEventListener("click", function() {
console.log("<html> (useCapture) clicked " + new Date().getTime(), this);
}, true);
bodyElement.addEventListener("click", function() {
console.log("<body> (useCapture) clicked " + new Date().getTime(), this);
}, true);
parentElement.addEventListener("click", function() {
console.log("Parent (useCapture) clicked " + new Date().getTime(), this);
}, true);
childElement.addEventListener("click", function() {
console.log("Child (useCapture) clicked at " + new Date().getTime(), this);
}, true);