Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Event Queue in JavaScript
Next article icon

Event Delegation in JavaScript

Last Updated : 27 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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);  


Next Article
Event Queue in JavaScript

N

NANDINIJAIN
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Misc

Similar Reads

  • Event Bubbling in JavaScript
    Event bubbling in JavaScript is a mechanism where an event triggered on a child element propagates upward through its ancestors in the DOM. It allows parent elements to respond to events triggered by their child elements. Propagation Direction: In event bubbling, the event starts at the target eleme
    6 min read
  • Pointer Events in Javascript DOM
    Pointer events are a set of DOM (Document Object Model) events that provide a unified way of handling inputs from a variety of devices, such as touchscreens, mouse, and pen/stylus. These events are supported by modern browsers and allow developers to write code that responds to user interactions wit
    5 min read
  • JavaScript Custom Events
    Events are used in almost every web application, such as the onclick event is used to execute some code when the user clicks on something. There are already numerous built-in events available to be used, but what if we want our custom event? Let us suppose we are creating a chat application, and we
    3 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, Ja
    5 min read
  • JavaScript Events
    JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. [GFGTABS] HTML <html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </
    3 min read
  • What is Event Bubbling and Capturing in JavaScript ?
    Events are a fundamental construct of the modern web. They are a special set of objects that allow for signaling that something has occurred within a website. By defining Event listeners, developers can run specific code as the events happen. This allows for implementing complex control logic on a w
    5 min read
  • What is An Event Loop in JavaScript?
    The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread. [GFGTABS] JavaScript console.log("Sta
    4 min read
  • Timing Events in Javascript
    Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
    5 min read
  • Explain invoking function in JavaScript
    In this article, we will learn about invoking the function in Javascript, along with understanding its implementation through examples. Function Invoking is a process to execute the code inside the function when some argument is passed to invoke it. You can invoke a function multiple times by declar
    2 min read
  • Foundation CSS JavaScript Events
    Foundation CSS JavaScript is a set of JavaScript tools and plugins that can be used to add interactivity and functionality to your website. It includes a variety of plugins for things like modals, alerts, and accordions, as well as utility functions for handling events and working with the DOM. Foun
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences