Event capturing and bubbling
by Marventus
HTML
<h2>Capturing Phase:</h2>
<div class="capture" id="abuelo">
<div class="capture" id="padre">
<div class="capture" id="hijo">
</div>
</div>
</div>
<h2>Bubbling Phase (default):</h2>
<div class="bubble" id="abuelo">
<div class="bubble" id="padre">
<div class="bubble" id="hijo">
</div>
</div>
</div>
CSS
div {
background: rgba(0,50,255, 0.3);
width: 100%;
}
#abuelo {
height: 150px;
}
#padre {
height: 100px;
}
#hijo {
height: 50px;
}
h2 {
color: #555;
font: bold 20px Arial, sans serif;
}
JavaScript
// Function alertId
var el = null;
function alertId() {
var $this = el !== null ? el : this;
console.log($this.getAttribute("id"));
}
// Bubbling (jQuery)
jQuery(function($) {
$(document).on("click", ".bubble", function(){
el = this;
alertId(el);
el = null;
});
});
// Capturing (Pure JS)
var divs = document.getElementsByClassName('capture');
for(var i=0; i<divs.length; i++) {
divs[i].addEventListener("click", alertId, true);
}