Javascript event bubble vs capture

Javascript/HTML events can propagate in two ways in DOM API. This is relevant when more than one element are listening on same event.

Event propagation type How it works
Event bubbling (default) Here event is handled by inner most element first. then it bubbles up.
Event capturing or trickling down Here event is handled by outermost element first and the it trickles down

Usage of addEventListener:

## For bubbling up: useCapture=false (default)
## For trickling down: useCapture=true
target.addEventListener(type, listener[, useCapture]);

Javascript event bubbling up example

Here outer and inner div both listening to click event. Since we are using useCapture=false, event will be handled by inner div and then bubble up. Note that we could also have skipped useCapture as the default value is false. Here is the screenshot of outcome after the click.
javascript-event-bubble-example

<div class="outer"><div class="inner">click here</div></div>
<div id="msg"></div>

<script type="text/javascript">
document.querySelector("div.outer").addEventListener("click", outer_click, false);
document.querySelector("div.inner").addEventListener("click", inner_click, false);
function outer_click(e) {
  document.querySelector("#msg").innerHTML += "In outer_click<br/>";
}
function inner_click(e) {
  document.querySelector("#msg").innerHTML += "In inner_click<br/>";
}
</script>
refresh

Javascript event tricking down example

Here outer and inner div both listening to click event. Since we are using useCapture=true, event will be handled by outer div and then trickle down. Here is the screenshot of outcome after the click.
javascript-event-capture-example

<div class="outer"><div class="inner">click here</div></div>
<div id="msg"></div>

<script type="text/javascript">
document.querySelector("div.outer").addEventListener("click", outer_click, true);
document.querySelector("div.inner").addEventListener("click", inner_click, true);
function outer_click(e) {
  document.querySelector("#msg").innerHTML += "In outer_click<br/>";
}
function inner_click(e) {
  document.querySelector("#msg").innerHTML += "In inner_click<br/>";
}
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments