Detailed summary of js bubbling capturing events and stopping bubbling methods

  • 2020-03-30 02:54:13
  • OfStack

The problems of event bubbling and event capture exist in the events of javascript and jquery. The two problems and their solutions are summarized in detail below.

Event bubbling is a bubbling process from child node to ancestor node.

Event capture is the opposite, from the ancestor node to the child node.

Give an example of a jquery click event:

The code is as follows:
<!DOCTYPE html> 
<meta charset="utf-8"> 
<script src=""></script> 
<script type="text/javascript"> 
<div style="width:100px;height:100px;background-color:red;"> 
<button type="button" id="button2">click me</button> 
<button id="clickMe">click</button> 

Event bubble phenomenon: click "id=clickMe" button, will appear "hello" and "baby" two pop-ups.

Analysis: when the button with "id=clickMe" is clicked, the click events bound to the button, the parent element of the button and the body of the button are triggered. Therefore, two boxes pop up successively and the so-called bubble phenomenon appears.

Event capture phenomenon: clicking on a div without a binding click event and on a button with "id=button2" will bring up the "baby" dialog.

In a real project, we would prevent event bubbling and event capture.

Methods to prevent event bubbling:

Method 1: return false in the current click event;

return false; 

Method 2:

var e = window.event || event; 

if ( e.stopPropagation ){ //If an event object is provided, this is a non-ie browser
//Compatible IE way to cancel event bubbling
window.event.cancelBubble = true; 

It seems that capture events cannot be stopped

Related articles: