The Wayback Machine - https://web.archive.org/web/20241002111757/https://www.geeksforgeeks.org/event-delegation-in-javascript/
Open In App

Event Delegation in JavaScript

Last Updated : 27 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Before learning about Event Delegation in JavaScript, we must be familiar with phases of JavaScript event https://www.geeksforgeeks.org/phases-of-javascript-event/

Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the .target property of the event object.

Let’s see an example with and without event delegation

const customUI = document.createElement('ul');

for (var i = 1; i <= 10; i++) {
    const newElement = document.createElement('li');
    newElement.textContent = "This is line " + i;
    newElement.addEventListener('click', () => {
        console.log('Responding')
    })
    customUI.appendChild(newElement);
}

The above code will associate the function with every <li> element that is shown in the below image. We are creating an <ul> element, attaching too many <li> elements, and attaching an event listener with a responding function to each paragraph as we create it.

Without Event Delegation

Implementing the same functionalities with an alternate approach. In this approach, we will associate the same function with all event listeners. We are creating too many responding functions (that all actually do the exact same thing). We could extract this function and just reference the function instead of creating too many functions:

const customUI = document.createElement('ul');

function responding() {
    console.log('Responding')
}

for (var i = 1; i <= 10; i++) {
    const newElement = document.createElement('li');
    newElement.textContent = "This is line " + i;
    newElement.addEventListener('click', responding)
    customUI.appendChild(newElement);
}

The functionality of the above code is shown below –

Without Event Delegation

In the above approach, we still have too many event listeners pointing to the same function. Now implementing the same functionalities using a single function and single event.

const customUI = document.createElement('ul');

function responding() {
    console.log('Responding')
}

for (var i = 1; i <= 10; i++) {
    const newElement = document.createElement('li');
    newElement.textContent = "This is line " + i;
    customUI.appendChild(newElement);
}
customUI.addEventListener('click', responding)

Now there is a single event listener and a single responding function. In the above-shown method, we have improved the performance, but we have lost access to individual <li> elements so to resolve this issue, we will use a technique called event delegation. 

The event object has a special property call .target which will help us in getting access to individual <li> elements with the help of phases.

Steps:

  • <ul> element is clicked.
  • The event goes in the capturing phase.
  • It reaches the target (<li> in our case).
  • It switches to the bubbling phase.
  • When it hits the <ul> element, it runs the event listener.
  • Inside the listener function event.target is the element that was clicked.
  • Event.target provides us access to the <li> element that was clicked.

The .nodeName property of the .target allows us to identify a specific node. If our parent element contains more than one child element then we can identify specific elements by using the .nodeName property.

const customUI = document.createElement('ul');

function responding(evt) {
    if (evt.target.nodeName === 'li')
        console.log('Responding')
}

for (var i = 1; i <= 10; i++) {
    const newElement = document.createElement('li');
    newElement.textContent = "This is line " + i;
    customUI.appendChild(newElement);
}

customUI.addEventListener('click', responding);


Similar Reads

What is Event bubbling and Event Capturing in JavaScript ?
Event bubbling and event capturing are the two interesting concepts of JavaScript. Before diving deep into these fascinating concepts, let us first know about what an event listener is? An event listener is basically a function that waits for an event to occur. That event can be anything like a mouse click event, submitting a form, pressing keys of
6 min read
What is the use of the Event.preventDefault() method in Event Handling in JavaScript ?
The Event.preventDefault() method in JavaScript is used within event handlers to prevent the default behavior associated with an event from taking place. When an event occurs, such as a click on a link or the submission of a form, there is often a default action associated with that event. preventDefault() allows developers to stop this default beh
1 min read
Difference between Event Bubling & Event Capturing ?
Event BubblingEvent bubbling is the default behavior in which an event triggered on a nested element propagates up through its ancestors in the DOM hierarchy, allowing each ancestor to respond to the event. Event Capturing Event capturing is the opposite of event bubbling, where the event is captured on the outermost ancestor first, and then it pro
1 min read
How to stop event propagation with inline onclick attribute in JavaScript ?
Use HTML DOM stopPropagation() method to stop the event from propagating with inline onclick attribute which is described below: HTML DOM stopPropagation() Event Method: The stopPropagation() method is used to stop propagation of event calling i.e. the parent event is called we can stop the propagation of calling its children by using the stopPropa
2 min read
Cross-browser window resize event using JavaScript/jQuery
The resize() method is an inbuilt method in jQuery that is used when the browser window changes its size. The resize() method triggers the resize event or attaches a function to run when a resize event occurs. jQuery has a built-in method for window resizing events. Syntax: $(selector).resize(function) This syntax is used for cross-browser resize e
2 min read
Phases of JavaScript Event
There are three different phases during the lifecycle of a JavaScript event. Capturing PhaseTarget PhaseBubbling Phase They follow the same order as listed above. Capturing Phase is when the event goes down to the element. The target phase is when the event reaches the element and the Bubbling phase is when the event bubbles up from the element. So
2 min read
What are the microtask and macrotask within an event loop in JavaScript ?
Event Loop: An Event Loop in JavaScript is said to be a constantly running process that keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are bro
4 min read
How to Pause and Play a Loop in JavaScript using Event Listeners ?
Given below is a JavaScript program for DOM manipulation which is basically about How to Pause and Play a loop in JavaScript using event listeners (not to be confused with delay). In this article, we are using JavaScript with HTML so we need a web browser i.e., Chrome (recommended) or Electron Application. Pausing and playing a loop is such a diffi
4 min read
Event Firing in JavaScript
What are Events?Events are actions or occurrences that happen in the system where we do programming, which the system tells you about so that we can respond to these events in some way if desired. For example, if the user selects a button on a webpage, one might want to respond to that action by displaying a dialog box. Understanding the basics of
3 min read
Which event occurs when a value is added to an input box in JavaScript?
JavaScript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model (DOM). These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We can bind events either as inline or in an external script. There are multiple events associated with Javascrip
2 min read
How to attach an event to an element which should be executed only once in JavaScript ?
In this article, we will learn how to attach an event to an element which should be executed only once. There are two approaches that can be used here: Approach 1: In this approach, we will be using the jQuery one() method. This method attaches an event to the element with the specified selector. It is named one because the event handler correspond
3 min read
Javascript Drag and Drop event - error catching
Javascript Drag and Drop event allows users to drag and drop elements within a web page. The event is initiated when the user clicks on an element and drags it to a new location. There are several other types of errors that can occur when working with the drag-and-drop event in Javascript. Here are a few examples: "Cannot read property 'setData' of
4 min read
Prevention from getting error by adding script tag anywhere using DOMContentLoaded Event Listener of JavaScript
In this article, we will see how can we prevent getting the error on the console by adding the script tag anywhere inside the body tag of HTML. On adding the script at the top we will be getting the error in a different form such that piece of code will not work on the page but the error will be displayed on the console of the developer menu. The b
4 min read
How to differentiate mouse “click” and “drag” event using JavaScript ?
Working with web elements a user may drag or click an element as per requirement. It is important to distinguish between drag and click events. JavaScript is a high-level, dynamically typed programming language that can be used to distinguish between drag and click events. JavaScript has drag-and-clicking events that help to differentiate between t
3 min read
Event Loop in JavaScript
In JavaScript, the event loop plays an important role in managing asynchronous operations and ensures the non-blocking behavior of the language. JavaScript is single-threaded, meaning it processes one task at a time and an event loop helps to handle asynchronous tasks efficiently. When an asynchronous operation, like a setTimeout callback or a user
1 min read
How to prevent the default action of an event in JavaScript ?
The term "default action" usually refers to the default behavior or action that occurs when an event is triggered. Sometimes, it becomes necessary to prevent a default action of an event. Let's create HTML structure with event and function that needs to prevent the default actions. C/C++ Code <!DOCTYPE html> <html lang="en">
3 min read
How to Call a JavaScript Function from an onsubmit Event ?
The onsubmit event attribute in HTML is triggered when a form is submitted. It is also useful for validating form data or performing actions before any submission and ensures better control and validation of user inputs before data is sent. The below methods can be used to call a JavaScript function from an onsubmit event: Table of Content Using on
2 min read
How to Call a JavaScript Function using an onsubmit Event ?
HTML has a form element that is used to get the data from the user and send the data to the server. Before the HTML form sends data to the server, it generates an event called "submit". This event can be utilized to execute a JavaScript function that can either validate the form data or notify the user of the form submission. Below are the approach
3 min read
How to Remove Event Handlers in JavaScript ?
In JavaScript, event handlers are functions attached to HTML elements to respond to specific events like clicks or mouse movements. Removing event handlers effectively detaches the specified function from listening to that particular event on that element. Table of Content Using removeEventListener()Using inline event handlersUsing removeEventListe
3 min read
How to call a JavaScript Function from an onmouseover Event ?
The onmouseover event in JavaScript is triggered when the mouse pointer moves onto an element, such as a button, image, or text. We will see how to call JavaScript function from an onmouseover event in various ways, like using the onmouseover Attribute and Using Event Listener. Table of Content Using onmouseover attributeUsing Event ListenerUsing t
2 min read
Event Queue in JavaScript
JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, JavaScript employs asynchronous behavior. Call Stack
5 min read
JavaScript onclick Event
The onclick event generally occurs when the user clicks on an element. It's a fundamental event handler in JavaScript, triggering actions or executing functions in response to user interaction, facilitating dynamic and interactive web functionality. In JavaScript, we can use the onclick function in two ways as listed below: Table of Content Applyin
2 min read
How to Call a JavaScript Function from an onmouseout Event ?
The onmouseout event in JavaScript triggers when the mouse pointer leaves an element. This event is commonly used in web development to execute certain functions when a user moves the mouse away from a specific area on the webpage. Below are the approaches to call a JavaScript function from an onmouseout event: Table of Content Using inline event h
3 min read
How to get the class of a element which has fired an event using JavaScript/JQuery?
One can use JavaScript and JQuery to retrieve the class of an element that triggers an event. By capturing the event and accessing the class attribute, developers can dynamically identify the specific element involved in the interaction. Below are the methods to get the class of an element that has fired an event: Table of Content Using JavaScriptU
3 min read
How to Add event listener to Button in JavaScript ?
In web development adding an event listener to a button is a common task that allows us to execute JavaScript code in response to user interactions, such as clicks. This helps us to create interactive and flexible web pages. Using addEventListener()The addEventListener method is a versatile and widely used way to attach event listeners to elements.
1 min read
How to Create Event Management Card using JavaScript and Tailwind CSS ?
An event management website is a platform designed to help users plan, organize, and promote events. It typically includes features such as event scheduling, ticket sales, attendee registration, and venue management. Building such a website with the Tailwind CSS can result in a sleek and modern user interface making it visually appealing and user-f
4 min read
What is the best way to add an event in JavaScript ?
Javascript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model(DOM). There are three ways to assign an event handler:  HTML event handler attributeHTML DOM propertyHTML DOM addEventListener() methodThe best way to add an event in JavaScript script is addEventListener(). Let's dive
2 min read
How to create Infinite Scrolling using onScroll Event in JavaScript?
We have seen many shopping sites that list some limited number of products(using a back-end API) when we open the website and scroll down to the bottom, we see that more products are fetched and displayed, and as we scroll even further even more products are loaded and fetched and it keeps happening till there are no more products to be displayed.
3 min read
How to add click event to Google Map markers stored in an array in JavaScript ?
To add a click event to markers stored in an array, you will first need to iterate over the array of markers using a loop. Then, within the loop, you can bind a click event to each marker. Syntax: var markers = [marker1, marker2, marker3]; // Array of markersfor (var i = 0; i < markers.length; i++) { // Bind a click event to the current marker m
3 min read
How to wait resize end event and then perform an action using JavaScript ?
When we resize the browser window, the "resize" event is fired continuously, multiple times while resizing. We want the "resize" event to only be fired once we are done resizing. Prerequisite: To solve this problem we use two functions:  setTimeout() functionclearTimeOut() functionExample: We will use setTimeout() so that the function in which we w
2 min read