Javascript how to stop event propagation

Javascript/HTML event can be handled by more than one dom elements and after one handler, it propagate to next element. API Event.stopPropagation() can be used to stop propagation of an event. It is best to avoid using stopProgation API as there might be other libraries on page which can get affected by this. In addition it is error prone.

Here is an example on how to use stop propagation. Here outer and two inner divs are listening to click event. One For inner1 div, we are using stopPropagation. So we we click on inner1 div, event is not propagated to outer div.

<div class="outer"><div class="inner1">click here (with stopPropagation)</div>
<div class="inner2">click here (without stopPropagation)</div></div>
<div id="msg"></div>

<script type="text/javascript">
document.querySelector("div.outer").addEventListener("click", outer_click, false);
document.querySelector("div.inner1").addEventListener("click", inner1_click, false);
document.querySelector("div.inner2").addEventListener("click", inner2_click, false);
function outer_click(e) {
  document.querySelector("#msg").innerHTML += "In outer_click<br/>";
}
function inner1_click(e) {
  document.querySelector("#msg").innerHTML += "In inner1_click<br/>";
  e.stopPropagation();
}
function inner2_click(e) {
  document.querySelector("#msg").innerHTML += "In inner2_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