JavaScript event delegation principle

JavaScript event delegation principle

1. What is event delegation?

Event delegation is also called event proxy. It is to use event bubbling to bind all events of child elements to parent elements. If the child element prevents the event from bubbling, then delegation cannot be achieved.

Here is a simple example:

For example, if a courier has 100 parcels to deliver to 100 students, it will take a long time to deliver them one by one. At the same time, each student needs to queue up to receive it, which takes a long time. How should it be done? At this time, the courier can entrust the 100 express parcels to the class teacher, who will put them in the office and the students can pick them up after class. In this way, the courier saves time and it is more convenient for students to receive the packages. This process is a delegation event.

2. The principle of event delegation

Instead of setting an event listener for each child node individually, the event listener is set on its parent node, and then the bubbling principle is used to affect the setting of each child node.

Let’s take a look at how it is implemented in a specific program!
For example, we now have an unordered list with five li in it. We want to add a click event to each li. At this time, our normal operation is to add a click event to each li through a loop.

The code looks like this:

<body>
    <ul>
        <li>111111</li>
        <li>222222</li>
        <li>333333</li>
        <li>444444</li>
        <li>555555</li>
    </ul>
    <script>
        var li = document.querySelectorAll('li');
        for(var i=0;i<li.length;i++){
            li[i].onclick = function(){
                this.style.color = 'green';
            }
        }
    </script>
</body>

The running results are:

This method can indeed realize our click operation, but in this process, since the click event must be added to li every time, it causes too many DOM accesses, which will prolong the interaction readiness time of the entire page.

So, here, we can use event delegation, that is, register the click event for ul, and then use the target of the event object to find the currently clicked li. Because when li is clicked, the event will bubble to ul, and if ul has a registered event, the event listener will be triggered.

The implementation code is:

<script>
        var ul = document.querySelector('ul');
        ul.addEventListener('click',function(e){
            e.target.style.color = 'orange';
        })
    </script>


The running results are:

Successfully displayed.

3. The role of event delegation

Through the above operations, we can get: in event delegation, we only operate DOM once, which greatly improves the performance of the program.

This is the end of this article about the principles of JavaScript event delegation. For more relevant JavaScript event delegation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of js event delegation
  • A brief analysis of event delegation examples in JS
  • js to realize web message board function
  • JavaScript to implement web message board function
  • Native JS implementation of message board
  • This article tells you how to use event delegation to implement JavaScript message board function

<<:  Detailed explanation of the solution to font blur when using transform in CSS3

>>:  HTML implementation of a simple calculator with detailed ideas

Recommend

Solutions to MySQL OOM (memory overflow)

OOM stands for "Out Of Memory", which m...

MySQL data backup and restore sample code

1. Data backup 1. Use mysqldump command to back u...

MySQL green version setting code and 1067 error details

MySQL green version setting code, and 1067 error ...

Detailed explanation of the basic usage of VUE watch listener

Table of contents 1. The following code is a simp...

Detailed explanation of MySQL master-slave database construction method

This article describes how to build a MySQL maste...

Analysis and practice of React server-side rendering principle

Most people have heard of the concept of server-s...

How to write object and param to play flash in firefox

Copy code The code is as follows: <object clas...

Detailed explanation of small state management based on React Hooks

Table of contents Implementing state sharing base...

Native JS implementation of loading progress bar

This article shares a dynamic loading progress ba...

How to set up the use of Chinese input method in Ubuntu 18.04

In the latest version of Ubuntu, users no longer ...

How to remove spaces or specified characters in a string in Shell

There are many methods on the Internet that, alth...

MySQL operations: JSON data type operations

In the previous article, we introduced the detail...

How to query and update the same table in MySQL database at the same time

In ordinary projects, I often encounter this prob...

MySQL multi-instance installation boot auto-start service configuration process

1.MySQL multiple instances MySQL multi-instance m...