In JavaScript dom operation, you will definitely encounter js bubbling events. The most common one is the div pop-up event as shown in the figure
When clicking on the gray part, the pop-up window disappears, and clicking on the black part has no effect.
Use the following code to analyze the bubbling event of js
html code:
The code copy is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js bubbling event</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<h1>js bubble event analysis</h1>
<hr>
<div>
<button>
Click me!
</button>
</div>
</div>
<script>
var box=document.querySelector(".box"),
btn=document.querySelector(".btn");
box.onclick=function(event){
alert("I am div");
}
btn.onclick=function(event){
alert("I am button");
}
</script>
</body>
</html>
Using the default developer tool of the firefox browser, the 3D view can clearly see the order of the div layer
Illustration:
When clicking the button, "I am a button" will pop up and "I am a div" will pop up, because the button event will be triggered first and then the next layer of div click event will be triggered.
The triggering of events is the first-in-first-out principle.
Illustration:
Then sometimes we don’t want multiple events to trigger conflicts, so event has a stopPropagation(); method to prevent bubbles.
There is also an event method that is also commonly used, such as a link. When I click on the link, I don’t want to jump, so I use the event.preventDefault(); method
The example code is as follows
The code copy is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js bubbling event</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<h1>js bubble event analysis</h1>
<hr>
<div>
<button>
Click me!
</button>
<a href="http://www.liteng.org" id="link">I am the link</a>
</div>
</div>
<script>
var box=document.querySelector(".box"),
btn=document.querySelector(".btn");
box.onclick=function(event){
alert("I am div");
}
btn.onclick=function(event){
alert("I am button");
event.stopPropagation();
}
document.getElementById('link').onclick=function(event){
alert("I am link");
event.preventDefault();
}
/*Distinguish between event.stopPropagation(); and event.preventDefault();
The former uses stopPropagation() method to prevent events from bubbled.
The latter is to block default behavior such as blocking hyperlinks
*/
</script>
</body>
</html>
Can you fully understand the bubbling incident of js? If you have any questions, please leave me a message