Javascript DOM Event cancelBubble() Method

Introduction

Prevent any bubbling of the current event:

Because DIV 1 is inside Div 2, both DIV elements get clicked when you click on DIV 1.

Check the cancel bubble checkbox, and try again.

The cancelBubble = true prevents the event flow from bubbling up to parent elements.

View in separate window

<!DOCTYPE html>
<html>
<body>
<style>
div {/*from  ww  w  .  ja v  a 2 s . co  m*/
  padding:50px;
  background-color:rgba(255, 0, 0, 0.2);
  text-align:center;
  cursor:pointer;
}
</style>

<p>Click DIV 1:</p>
<div onclick="func2()">DIV 2
  <div onclick="func1(event)">DIV 1</div>
</div>

Cancel bubble:
<input type="checkbox" id="check">
<p></p>

<p id="demo"></p>


<script>
function func1(event) {
  document.getElementById("demo").innerHTML = "DIV 1";
  if (document.getElementById("check").checked) {
    event.cancelBubble = true;
  }
}

function func2() {
  document.getElementById("demo").innerHTML = "DIV 2";
}
</script>

</body>
</html>

The cancelBubble() method prevents the event-flow from bubbling up to parent elements.

To prevent both bubbling up to parent elements and capturing down to child elements, use the stopPropagation() method instead.




PreviousNext

Related