Quick solution for JS bubbling events

  • 2020-03-30 00:56:06
  • OfStack

What is a bubble event
This is when you have multiple divs nested; That is, a parent-child relationship is established. When the parent div and the child div join the onclick event together, when the onclick event of the child div is triggered, the child div carries out the corresponding js operation. But the onclick event for the parent div is also triggered. This results in multiple levels of concurrency of events, resulting in page clutter. This is the bubbling event.

Methods to eliminate bubbling events
Prevent JavaScript event bubble propagation (cancelBubble, stopPropagation)

The following code is a good explanation of the bubble effect, what is the elimination of bubble effect


<html> 
<head> 
<title>  stop JavaScript Event bubbling ( cancelBubble  , stopPropagation ) </title> 
<meta name="keywords" content="JavaScript, The event bubbling ,cancelBubble,stopPropagation" /> 
<script type="text/javascript"> 
function doSomething (obj,evt) { 
alert(obj.id); 
var e=(evt)?evt:window.event; //To determine the type of browser, use cancelBubble in browsers based on the ie kernel
if (window.event) { 
e.cancelBubble=true; 
} else { 
//e.preventDefault(); // Based on the firefox The kernel supports this in the browser stopPropagation
e.stopPropagation(); 
} 
} 
</script> 
</head> 
<body> 
<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow"> 
<p>This is parent1 div.</p> 
<div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange"> 
<p>This is child1.</p> 
</div> 
<p>This is parent1 div.</p> 
</div> 
<br /> 
<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;"> 
<p>This is parent2 div.</p> 
<div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;"> 
<p>This is child2. Will bubble.</p> 
</div> 
<p>This is parent2 div.</p> 
</div> 
</body> 
</html>

After you copy the code directly, open and when you click on child1, not only does it bring up the child1 dialog box, but it also brings up parent1

This is the bubbling event

But clicking on chile2 brings up child2 but not parent2, which is what happens when special effects are applied to prevent bubbling events.


Related articles: