Javascript DOM Event stopPropagation() Method

Introduction

Prevent any propagation of the same event:

View in separate window

<!DOCTYPE html>
<html>
<body>
<style>
div {//  w  w  w .ja va2  s .c o  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>

Stop propagation:
<input type="checkbox" id="check">

<p></p>

<p>Because DIV 1 is inside Div 2, both DIVs get clicked when you click on DIV 1.</p>
<p>Check the stop propagation checkbox, and try again.</p>

<p id="demo"></p>
<script>
function func1(event) {
  document.getElementById("demo").innerHTML = "DIV 1";
  if (document.getElementById("check").checked) {
    event.stopPropagation();
  }
}

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

</body>
</html>

The stopPropagation() method prevents bubbling up to parent elements or capturing down to child elements.




PreviousNext

Related