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

Full process record of Nginx reverse proxy configuration

1. Preparation Install Tomcat on Linux system, us...

10 tips for designing useful, easy-to-use web applications

Here are 10 tips on how to design better-usable w...

CSS3 realizes the red envelope shaking effect

There is a requirement to realize the shaking eff...

Issues with Rancher deployment and importing K8S clusters

Rancher deployment can have three architectures: ...

A brief discussion on the pitfalls of react useEffect closure

Problem code Look at a closure problem code cause...

Introduction to MySQL method of deleting table data with foreign key constraints

When deleting a table or a piece of data in MySQL...

Docker automated build Automated Build implementation process diagram

Automated build means using Docker Hub to connect...

Nginx uses reverse proxy to implement load balancing process analysis

Introduction Based on docker container and docker...

Detailed explanation of daily_routine example code in Linux

First look at the example code: #/bin/bash cal da...

HTML discount price calculation implementation principle and script code

Copy code The code is as follows: <!DOCTYPE HT...

Several methods of implementing carousel images in JS

Carousel The main idea is: In the large container...

Some parameter descriptions of text input boxes in web design

<br />In general guestbooks, forums and othe...

mysql5.7 installation and configuration tutorial under Centos7.3

This article shares the MySQL 5.7 installation an...

Solution to the problem of not finding Tomcat configuration in Intelli Idea

I joined a new company these two days. The compan...