惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
JavaScript Event Delegation: A Beginner's Guide
Dmitri Pavlutin · 2020-07-14 · via Dmitri Pavlutin Blog

Event delegation is a useful pattern because it allows listening for events on many elements with just one event listener.

Let's see how event delegation works.

1. Why event delegation?

Let's log a message to the console when an HTML button is clicked.

To make it work, you need to select the button, then use addEventListener() method to attach an event listener:


<button id="buttonId">Click me</button>

<script>

document.getElementById('buttonId')

.addEventListener('click', () => console.log('Clicked!'));

</script>


That's the way to go to listen for events on a single element, particularly a button.

What about listening for events on multiple buttons? Here's a possible implementation:


<div id="buttons">

<button class="buttonClass">Click me</button>

<button class="buttonClass">Click me</button>

<!-- buttons... -->

<button class="buttonClass">Click me</button>

</div>

<script>

const buttons = document.getElementsByClassName('buttonClass');

for (const button of buttons) {

button.addEventListener('click', () => console.log('Clicked!'));

}

</script>


Take a look at the Codesandbox demo to see how it works.

The buttons list is iterated for (const button of buttons) and a new listener is attached to each button. Also, when a button is added or removed from the list, you'd have to manually remove or attach event listeners.

Is there a better approach?

Fortunately, when using the event delegation pattern, listening for events on multiple elements requires just one event listener.

The event delegation uses specifics of the event propagation mechanism. To understand how event delegation works, it is important to understand the event propagation first.

2. Event propagation

When you click the button in the following HTML:


<html>

<body>

<div id="buttons">

<button class="buttonClass">Click me</button>

</div>

</body>

</html>


On how many elements does the click event gets triggered? Without a doubt, the button itself receives a click event. But also... all button's ancestors, and document, and window.

A click event propagates in 3 phases:

  1. Capture phase — Starting from window, document, and the root element, the event dives down through ancestors of the target element
  2. Target phase — The event gets triggered on the element on which the user has clicked
  3. Bubble phase — Finally, the event bubbles up through ancestors of the target element until the root element, document, and window.

JavaScript Event Propagation

The third argument captureOrOptions of the method:


element.addEventListener(eventType, handler[, captureOrOptions]);


lets you catch events from different phases.

  • If captureOrOptions argument is missing, false or { capture: false }, then the listener captures the events of target and bubble phases
  • If the argument is true or { capture: true }, then the listener listens for events of capture phase.

The following event handler listens for click events in the capture phase that occured on <body> element:


document.body.addEventListener('click', () => {

console.log('Body click event in capture phase');

}, true);


In this Codesandbox demo, when clicking the button, you can see in console how the event propagates.

Ok, how does event propagation help capture events of multiple buttons?

The algorithm is simple:

  1. Attach the event listener to the parent element of buttons
  2. Catch the bubbling event when the button is clicked.

This is how event delegation works.

3. Event delegation

Let's use the event delegation to catch clicks on multiple buttons:


<div id="buttons"> <!-- Step 1 -->

<button class="buttonClass">Click me</button>

<button class="buttonClass">Click me</button>

<!-- buttons... -->

<button class="buttonClass">Click me</button>

</div>

<script>

document.getElementById('buttons')

.addEventListener('click', event => { // Step 2

if (event.target.className === 'buttonClass') { // Step 3

console.log('Click!');

}

});

</script>


Open the Codesandbox demo and click any button — you'll see 'Click!' message logged to console.

Instead of attaching the event listeners directly to the buttons, you delegate listening to the parent <div id="buttons">. When a button is clicked, the click event bubbles and the listener of the parent element catches it (recall the event propagation?).

Using the event delegation requires 3 steps:

Step 1. Determine the parent of elements to watch for events

In the example above, <div id="buttons"> is the parent element of the buttons.

Step 2. Attach the event listener to the parent element

document.getElementById('buttons') .addEventListener('click', handler) attaches the event listener to the parent element of buttons. This listener reacts to button clicks because the button click event bubbles through ancestors (thanks to the event propagation).

Step 3. Use event.target to select the target element

When a button is clicked, the handler function is invoked with an argument: the event object. The property event.target is the element upon which the event has been dispatched, which in the example is a button:


// ...

.addEventListener('click', event => {

if (event.target.className === 'buttonClass') {

console.log('Click!');

}

});


Now you can see the benefit of the event delegation pattern: instead of attaching listeners to every button like it was done earlier, thanks to event delegation just one event listener is necessary.

(As a side note, event.currentTarget points to the element to which the event listener is attached directly. In the example, event.currentTarget is <div id="buttons">.)

4. Summary

When a click event happens (or any other event that propagates):

  • The event travels down from window, document, root element and through the ancestors of the target element (capture phase)
  • The event occurs on the target (the target phase)
  • Finally, the event bubbles up through the target's ancestors until the root element, document and window (the bubble phase).

This is event propagation.

The event delegation is a useful pattern because you can listen for events on multiple elements using one event handler.

Making the event delegation work requires 3 steps:

  1. Determine the parent of elements to watch for events
  2. Attach the event listener to the parent element
  3. Use event.target to select the target elements

Do you have any questions regarding the event propagation or event delegation? If so, please write a comment below!