For HTML:
<div id="level1">
<div id="level2">
<div id="level3">
Dummy
</div>
</div>
</div>
; and event handlers for all div's:
$('#level1').on('click',function(event){
console.log("level1");
});
$('#level2').on('click',function(event){
console.log("level2");
});
$('#level3').on('click',function(event){
console.log("level3");
});
; event click will be first handled in innermost level3 and then bubbled up to its parents.
level3
level2
level1
To prevent event bubbling we use event.stopPropagation();
When placed in level3 other levels wont get executed:
level3
Modern browsers support alternative propagation model - capturing. When writing event handler it must be explicitly specified. Capturing works opposite from bubbling. It first handles outermost elements and then executes all children handlers.
For years I've believed that: event.preventDefault() is preventing event bubbling.
For this href:
<a href="www.google.com">Google</a>
; and event handler:
$('a').on('click',function(event){
event.preventDefault();
console.log("google.com");
})
; it prevents standard browser action for HREF so no redirect happens.
No comments:
Post a Comment