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

VUE+Canvas implements the sample code of the desktop pinball brick-breaking game

Everyone has played the pinball and brick-breakin...

How to solve the problem of too many open files in Linux

The cause is that the process opens a number of f...

Detailed explanation of the usage of 5 different values ​​of CSS position

The position property The position property speci...

Web design dimensions and rules for advertising design on web pages

1. Under 800*600, if the width of the web page is...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

Detailed use cases of vue3 teleport

Official Website https://cli.vuejs.org/en/guide/ ...

It's the end of the year, is your MySQL password safe?

Preface: It’s the end of the year, isn’t it time ...

Four ways to switch tab pages in VUE

Table of contents 1. Static implementation method...

Building a selenium distributed environment based on docker

1. Download the image docker pull selenium/hub do...

5 VueUse libraries that can speed up development (summary)

Table of contents What utilities does VueUse have...

Talk about important subdirectory issues in Linux system

/etc/fstab Automatically mount partitions/disks, ...

How to use bind to set up DNS server

DNS (Domain Name Server) is a server that convert...