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

JavaScript selector functions querySelector and querySelectorAll

Table of contents 1. querySelector queries a sing...

How to view and optimize MySql indexes

MySQL supports hash and btree indexes. InnoDB and...

Web page html special symbols html special characters comparison table

Special symbols Named Entities Decimal encoding S...

MySql learning day03: connection and query details between data tables

Primary Key: Keyword: primary key Features: canno...

10 Underused or Misunderstood HTML Tags

Here are 10 HTML tags that are underused or misun...

How to use Spark and Scala to analyze Apache access logs

Install First you need to install Java and Scala,...

React+TypeScript project construction case explanation

React project building can be very simple, but if...

Use pictures to realize personalized underline of hyperlinks

Don't be surprised if you see some kind of und...

Example of nginx ip blacklist dynamic ban

When a website is maliciously requested, blacklis...

How to install jupyter in docker on centos and open ports

Table of contents Install jupyter Docker port map...

JavaScript commonly used array deduplication actual combat source code

Array deduplication is usually encountered during...

Pure HTML+CSS to achieve Element loading effect

This is the effect of the Element UI loading comp...