Detailed examples of using JavaScript event delegation (proxy)

Detailed examples of using JavaScript event delegation (proxy)

Introduction

illustrate

This article uses examples to introduce the usage of delegation (delegate) of events in JavaScript.

Introduction to event delegation

Event delegation, also called event proxy, is a common technique for binding events in JavaScript. It is to delegate the response events that originally need to be bound to the child elements to the parent elements or outer elements, so that the outer elements can take on the responsibility of event monitoring.

The principle of event delegation is event bubbling of DOM elements.

Advantages of event delegation

1. Save memory and reduce event binding

Originally, events needed to be bound to all child elements, but after using event delegation, only one event binding is required.

2. Events can be dynamically bound, and newly added sub-object events can be processed by bound events

Because the events generated by the newly added child objects will eventually bubble up to the parent element, so that they can be handled

Example: Event delegation

Requirement: A list whose contents pop up when a list element is clicked.

Writing method 1: event delegation

Just bind the event to the outer element.

 <!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>I am the first li</li>
    <li>I am the second li</li>
    <li>I am the third li</li>
</ul>
 
<script>
    let ul = document.getElementById('id-ul');
    ul.addEventListener("click", function (ev) {
        alert(ev.target.innerText);
    })
</script>
 
</body>
</html>

result

Writing method 2: Each child element is bound to an event

Each child element has events bound to it.

 <!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>I am the first li</li>
    <li>I am the second li</li>
    <li>I am the third li</li>
</ul>
 
<script>
    let li = document.querySelectorAll('#id-ul li');
    for (let liElement of li) {
        liElement.addEventListener("click", function (ev) {
            alert(ev.target.innerText);
        });
    }
</script>
 
</body>
</html>

result

Example: Adding a new element

Requirement: Every time you click the "Generate Button", a sub-list element is generated. Then, each time you click on a list element, its contents will pop up.

Writing method 1: event delegation

 <!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>1</li>
    <li>2</li>
</ul>
<button id="btn">click</button>
<script>
    let num = 3;
    let eUl = document.querySelector("#id-ul");
    let eButton = document.querySelector("#btn");
 
    eButton.addEventListener("click", function () {
        let newLi = document.createElement("li");
        eUl.appendChild(newLi);
        newLi.innerText = num++;
    })
    eUl.addEventListener("click",function (event) {
        alert(event.target.innerText);
    })
</script>
 
</body>
</html>

result

As you can see, events of both existing elements and newly created elements will be processed.

Writing method 2: Each child element is bound to an event

 <!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>1</li>
    <li>2</li>
</ul>
<button id="btn">click</button>
<script>
    let num = 3;
    let eUl = document.querySelector("#id-ul");
    let eButton = document.querySelector("#btn");
    let eLi = document.querySelectorAll("#id-ul li");
 
    eButton.addEventListener("click", function () {
        let newLi = document.createElement("li");
        eUl.appendChild(newLi);
        newLi.innerText = num++;
    })
 
    for (let eLiElement of eLi) {
        eLiElement.addEventListener("click",function (event) {
            alert(event.target.innerText);
        })
    }
 
</script>
 
</body>
</html>

result

You can see that the click events of the original elements will be processed, but the newly added ones will not be processed.

This concludes this article on the detailed usage examples 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 you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript event delegation principle
  • Detailed explanation of js event delegation
  • JavaScript event delegation principle and usage example analysis
  • js event delegation and event proxy case sharing
  • Detailed explanation of js event proxy (delegate)
  • JS event binding, event monitoring, and event delegation in detail

<<:  Image scrolling effect made with CSS3

>>:  HTML+Sass implements HambergurMenu (hamburger menu)

Recommend

MySQL recursion problem

MySQL itself does not support recursive syntax, b...

Causes and solutions to the garbled character set problem in MySQL database

Preface Sometimes when we view database data, we ...

Summary of common functions and usage methods of WeChat applet development

Here, I have mainly sorted out some commonly used...

Specific use of MySQL segmentation function substring()

There are four main MySQL string interception fun...

IE8 uses multi-compatibility mode to display web pages normally

IE8 will have multiple compatibility modes . IE pl...

Introduction to the use and disabling of transparent huge pages in Linux

introduction As computing needs continue to grow,...

Web page CSS priority is explained in detail for you

Before talking about CSS priority, we need to und...

Example code of layim integrating right-click menu in JavaScript

Table of contents 1. Effect Demonstration 2. Impl...

SQL implementation of LeetCode (182. Duplicate mailboxes)

[LeetCode] 182.Duplicate Emails Write a SQL query...

The concept of MTR in MySQL

MTR stands for Mini-Transaction. As the name sugg...

How to install mysql on centos and set up remote access

1. Download the mysql repo source $ wget http://r...

Modification of the default source sources.list file of ubuntu20.04 LTS system

If you accidentally modify the source.list conten...

express project file directory description and detailed function description

app.js: startup file, or entry file package.json:...

Implementation of Single Div drawing techniques in CSS

You can often see articles about CSS drawing, suc...