zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Event listener functions, as well as the event capturing and bubbling mechanisms

Events are generally used for interaction between the browser and user operations. When a user performs certain special actions, the browser responds and triggers the bound events. The event flow refers to the propagation of events between element nodes and the root node in a specified order when an event occurs. All nodes that the event passes through will be affected by the event, and this propagation process is called the DOM event flow.

Function Events#

Events are generally used for interaction between the browser and user operations. When a user performs certain special actions, the browser responds and triggers the bound events.

The event flow refers to the propagation of events between element nodes and the root node in a specified order when an event occurs. All nodes that the event passes through will be affected by the event, and this propagation process is called the DOM event flow.

image

true is for capture, false is for bubbling, and the default is bubbling.

1. addEventListener() - Adding Event Listener Functions#

Add an event to an element. If there are multiple events, they will not overwrite each other and will execute in sequence.

<div id="demo">dom</div>
<script>
    document.getElementById('demo').addEventListener("click", myfun)
    document.getElementById('demo').addEventListener("click", myfun1)

    function myfun() {
        console.log('Event listener function')
    }

    function myfun1() {
        console.log('addEventListener')
    }
</script>

image

Note:

  1. There is a detail here: addEventListener() has two parameters, the first indicates the triggering condition, and the second indicates the event to be triggered.
    Under normal circumstances, the second parameter should directly write the function name without adding (). If () is added, it indicates immediate execution without needing to meet the conditions required by the first parameter.
  1. When binding events here, the event name cannot be the same as the defined variable name; otherwise, it will be ineffective.

2. removeEventListener() - Removing Event Listener Functions#

In the following demo, when the mouse moves within the div, a random number appears. After clicking the button, the event listener function is removed.

<!-- css -->
<style>
    #demo {
        width: 100px;
        height: 100px;
        border: 1px solid #000;
    }
</style>

<!-- html -->
<div id="demo"></div>
<input type="button" value="Click to Remove" onclick="remove()">
<div id="show"></div>

<!-- js -->
<script>
    document.getElementById('demo').addEventListener("mousemove", myfun)
    function myfun() {
        document.getElementById('show').innerHTML = Math.random()
    }

    function remove() {
        document.getElementById('demo').removeEventListener("mousemove", myfun)
    }
</script>

3. Doing Something with Event Capture and Bubbling#

addEventListener() and removeEventListener() actually have three parameters. As mentioned earlier, the first indicates the triggering condition, the second indicates the event to be triggered, and the third parameter can usually be omitted, but it is important to know what it represents.

It is represented by a boolean value, true or false, with the default being false.

image

  • true indicates that the event handler is called during the capture phase.
  • false indicates that the event handler is called during the bubbling phase.

From the image, it can be seen that the capture phase occurs before the bubbling phase. Therefore, true events are triggered before false events, and multiple true events are triggered in order, while multiple false events are triggered with the later ones first.

Conclusion: Events written earlier with true > Events written later with true > Events written later with false > Events written earlier with false.

Thus, using this parameter, you can control the order of triggering different events on the same element.

<div id="out">
    <p>Outermost</p>
    <div id="middle">
        <div id="inner">Innermost</div>
    </div>
</div>

<!-- First Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: inner-------middle------out
    out.addEventListener('click',function(){alert("I am the outermost");},false);   
    middle.addEventListener('click',function(){alert("I am the middle");},false);    
    inner.addEventListener('click',function(){alert("I am the innermost");},false); 
</script>

<!-- Second Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: out------middle-------inner
    out.addEventListener('click',function(){alert("I am the outermost");},true);   
    middle.addEventListener('click',function(){alert("I am the middle");},true);  
    inner.addEventListener('click',function(){alert("I am the innermost");},true); 
</script>

<!-- Third Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: out------inner-------middle
    out.addEventListener('click',function(){alert("I am the outermost");},true);   
    middle.addEventListener('click',function(){alert("I am the middle");},false);    
    inner.addEventListener('click',function(){alert("I am the innermost");},false);
</script>

<!-- Fourth Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: out-------middle------inner
    out.addEventListener('click',function(){alert("I am the outermost");},true);   
    middle.addEventListener('click',function(){alert("I am the middle");},true);  
    inner.addEventListener('click',function(){alert("I am the innermost");},false);
</script>

<!-- Fifth Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: middle-------inner------out
    out.addEventListener('click',function(){alert("I am the outermost");},false);   
    middle.addEventListener('click',function(){alert("I am the middle");},true);  
    inner.addEventListener('click',function(){alert("I am the innermost");},false);
</script>

<!-- Sixth Case -->
<script>
    var out = document.getElementById('out'); 
    var middle = document.getElementById('middle'); 
    var inner = document.getElementById('inner'); 
    // When clicking inner, the trigger order is: out-------inner------middle
    out.addEventListener('click',function(){alert("I am the outermost");},true);   
    middle.addEventListener('click',function(){alert("I am the middle");},false);    
    inner.addEventListener('click',function(){alert("I am the innermost");},true);
</script>

4. Event Handlers#

  1. HTML Event Handlers
<button onclick="test()">Test</button>
<script>
    function test() {
        alert("HTML Event Handler");
    }
</script>
  1. Advantages: The code in the event handler can access any variable in the global scope.
  2. Disadvantages: Timing issues, extended scope chains can lead to different results in different browsers, and high coupling between HTML and JS code.
  1. DOM Level 0 Event Handlers
<button id="btn">Test</button>
<script>
    var btn = document.getElementById("btn");
    btn.onclick = function test() {
        alert("DOM Level 0 Event Handler");
    }
</script>
  1. Advantages: Simple code, good browser compatibility, solves the high coupling problem between HTML and JS code.
  2. Disadvantages: An element can only bind one event handler and will only run during event bubbling.
  1. DOM Level 2 Event Handlers

This level of event handlers utilizes the event capture and bubbling mechanisms.

<button id="btn">Test</button>
<script>
    var btn = document.getElementById("btn");

    // Event listener
    btn.addEventListener("click", function() {
        alert("DOM Level 2 Event Handler, I execute in the capture phase");
    }, true);

    btn.addEventListener("click", function() {
        alert("DOM Level 2 Event Handler, I execute in the bubbling phase");
    }, false);

    // Remove event listener
    var fun = function() {
        alert("I will be removed");
    }
    btn.addEventListener("click", fun, false);
    btn.removeEventListener("click", fun, false);
</script>
  1. Advantages: Supports both capture and bubbling phases for event handling, and an element can bind multiple handler functions.
  2. Disadvantages: Not supported by IE.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.