Bind Event Sequence in JS (Difference between Event Bubbling and Event Capture)

  • 2021-07-15 03:40:39
  • OfStack

In JS, the default execution time of bound events is in the bubble phase, not in the capture phase (important), which is why when both the parent class and the subclass are bound to an event, the event bound by the subclass will be called first, and then the event of the parent class will be called. Look directly at the following example


<!Doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title></title>
 <style type="text/css">
 *{margin:0;padding: 0;}
 </style>
</head>
<body>
<div id="id1" style="height:400px; border:1px solid #000;">
 <div id="id2" style="height:200px; border:1px solid #000;">
 <div id="id3" style="height:50px; border:1px solid #000;"></div>
 </div>
</div>
</body>
<script type="text/javascript">
 var obj1=document.getElementById('id1'); 
 obj1.addEventListener('click',function(){
 alert('id1');
 },false);
 var obj2=document.getElementById('id2');
 obj2.addEventListener('click',function(){
 alert('id2');
 },true);
 var obj3=document.getElementById('id3');
 obj3.addEventListener('click',function(){
 alert('id3');
 },true);
 /* If the 3 Parameters are true The event executes during the capture phase if the 3 Parameters are false The event is executed during the bubble phase */
</script>
</html>

When the id3 element is clicked, the execution results are: id2, id3, id1

Parsing: Because the obj2-obj3-bound method executes in the capture phase, the obj1 event executes in the bubble phase.

Summarize

In JS, the default execution time of bound events is in the bubble phase, not in the capture phase. It must be understood that

However, when binding events, we can specify whether the event execution time is in the bubble phase or the capture phase.

obj.addEventListener(event,function(){},bool)

bool: false for bubble phase execution

bool: true, representing capture phase execution

After JS gets an event by default, it starts capturing all listener objects for the event from the root element, and then executes one-by-one in the bubbling phase. The capture phase is preceded by the bubbling phase

Prevent bubbling

The method of w3c is e. stopPropagation (), and IE is e. cancelBubble = true;

Block default behavior

The method of w3c is e. preventDefault (), and IE uses e. returnValue = false;

On JS Event Bubble and onclick, click, on () Event Trigger Sequence

Priority relationship of onclick, click, on (): onclick > click > on ();

Events bound by onclick and click follow the event bubbling rule and trigger from inside to outside;

Events bound to on () are always triggered later than events bound to onclick and click;


Related articles: