Example of using the stopPropagation function to stop event propagation in JavaScript

  • 2020-03-30 03:46:02
  • OfStack

Events in JS are bubbling by default, propagating layer by layer, and the propagation of events in DOM hierarchy can be stopped through the stopPropagation() function. As the following example:

HTML code:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>stopPropagation() use  -  Joan Taiwan blog </title>
</head>
<body>
<button>button</button>
</body>
</html>
[/code] 
 without stopPropagation()
[code]
var button = document.getElementsByTagName('button')[0];
button.onclick=function(event){
  alert('button click');
};
 
document.body.onclick=function(event){
  alert('body click');
}

The DOM propagates layer by layer, so the click on the button button also propagates to the body layer, and the click on the body layer responds. The result is two warning boxes, button and body.

Added stopPropagation ()


var button = document.getElementsByTagName('button')[0];
button.onclick=function(event){
  alert('button click');
  //Stop DOM event level propagation
  event.stopPropagation();
};
 
document.body.onclick=function(event){
  alert('body click');
}

The stopPropagation() stop event propagation function is used in the click event handler of the button, so after the warning box from the button click event pops up, the body cannot be propagated, and the warning box of the body will not pop up again. As a result, the warning box is only discussed once.

A lot of children's shoes in writing JS, often ignore the DOM event layer by layer up the propagation of the characteristics, resulting in abnormal procedures. If you need more in-depth information, you can look for information on JS event bubbling.


Related articles: