search
HomeWeb Front-endJS TutorialTechnical principles of JavaScript event delegation

Technical principles of JavaScript event delegation

Jun 17, 2020 pm 04:08 PM
javascriptevent delegation

Technical principles of JavaScript event delegation

One of the hottest technologies in today’s JavaScript technology world should be ‘event delegation’. Using event delegation techniques allows you to avoid adding event listeners to specific each node; instead, event listeners are added to their parent elements. The event listener will analyze the events that bubble up from the child elements and find out which child element the event is from. The basic concept is very simple, but there are still many people who don't understand how event delegation works. Here I'm going to explain how event delegation works and provide a few examples of basic event delegation in pure JavaScript.

Suppose we have a UL element with several sub-elements:

<ul id="parent-list">
	<li id="post-1">Item 1</li>
	<li id="post-2">Item 2</li>
	<li id="post-3">Item 3</li>
	<li id="post-4">Item 4</li>
	<li id="post-5">Item 5</li>
	<li id="post-6">Item 6</li>
</ul>

We also assume that when each sub-element is clicked, there will be a different event occurs. You can add event listeners to each independent li element, but sometimes these li elements may be deleted or added, and listen for their new or deleted events. This can be a nightmare, especially if your event-listening code is in another part of your application. But what if you place listeners on their parent elements? How do you know which child element was clicked?

Simple: When a child element's event bubbles up to the parent ul element, you can check the target property of the event object to capture a reference to the node element that was actually clicked. The following is a very simple JavaScript code that demonstrates the process of event delegation:

// 找到父元素,添加监听器...
document.getElementById("parent-list").addEventListener("click",function(e) {
	// e.target是被点击的元素!
	// 如果被点击的是li元素
	if(e.target && e.target.nodeName == "LI") {
		// 找到目标,输出ID!
		console.log("List item ",e.target.id.replace("post-")," was clicked!");
	}
});

The first step is to add an event listener to the parent element. When an event triggers the listener, check the source of the event and exclude non-li child element events. If it is a li element, we have found the target! If not a li element, the event will be ignored. This example is very simple, UL and li are standard parent-child combinations. Let's experiment with some different combinations of elements. Suppose we have a parent element p, which has many child elements, but what we care about is the A tag with the "classA" CSS class inside:

// 获得父元素p, 添加监听器...
document.getElementById("myp").addEventListener("click",function(e) {
	// e.target是被点击的元素
	if(e.target && e.target.nodeName == "A") {
		// 获得CSS类名
		var classes = e.target.className.split(" ");
		// 搜索匹配!
		if(classes) {
			// For every CSS class the element has...
			for(var x = 0; x < classes.length; x++) {
				// If it has the CSS class we want...
				if(classes[x] == "classA") {
					// Bingo!
					console.log("Anchor element clicked!");

					// Now do something here....

				}
			}
		}

	}
});

In the above example Not only the tag names are compared, but also the CSS class names. Although it is a little more complicated, it is still very representative. For example, if there is a span tag in an A tag, this span will become the target element. At this time, we need to trace up the DOM tree structure to find out whether there is an A.classA element in it.

Because most programmers will use tool libraries such as jQuery to handle DOM elements and events, I recommend that everyone use the event delegation method inside, because the tool library here provides advanced delegation methods and element screening. method.

I hope this article can help you understand the behind-the-scenes principles of JavaScript event delegation, and I hope you also feel the powerful use of event delegation!

(English: davidwalsh.)

Recommended tutorial: "javascript basic tutorial"

The above is the detailed content of Technical principles of JavaScript event delegation. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:webhek. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools