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

Detailed steps for setting up and configuring nis domain services on Centos8

Table of contents Introduction to NIS Network env...

VUE introduces the implementation of using G2 charts

Table of contents About G2 Chart use Complete cod...

Book page turning effects made with CSS3

Result:Implementation code: html <!-- Please h...

How to understand Vue front-end and back-end data interaction and display

Table of contents 1. Technical Overview 2. Techni...

HTML Tutorial: DOCTYPE Abbreviation

When writing HTML code, the first line should be ...

HTML page jump and parameter transfer issues

HTML page jump: window.open(url, "", &q...

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction Vue.js allows you to define...

JavaScript implementation of classic snake game

This article shares the specific code of JavaScri...

Detailed explanation of Vue slot

1. Function : Allows the parent component to inse...

JavaScript to achieve product magnifying glass effect

This article shares the specific code of JavaScri...

js to achieve interesting countdown effect

js interesting countdown case, for your reference...

Ubuntu 16.04 mysql5.7.17 open remote port 3306

Enable remote access to MySQL By default, MySQL u...

MySQL compression usage scenarios and solutions

Introduction Describes the use cases and solution...

Summary of commonly used commands for docker competition submission

Log in to your account export DOCKER_REGISTRY=reg...