{"id":3468,"date":"2018-04-19T10:00:31","date_gmt":"2018-04-19T04:30:31","guid":{"rendered":"https:\/\/code4developers.com\/?p=3468"},"modified":"2018-05-09T11:32:49","modified_gmt":"2018-05-09T06:02:49","slug":"event-delegation-javascript","status":"publish","type":"post","link":"https:\/\/code4developers.com\/event-delegation-javascript\/","title":{"rendered":"Event Delegation in JavaScript"},"content":{"rendered":"<p>Event delegation is a pattern of adding an event listener to a parent node instead, of adding an event listener to the individual node. The added event listener will check for the bubbled event to find matching child element. In this article we will talk about how to implement an event listener using very trending method in JavaScript i.e., event delegation pattern.<\/p>\n<p><!--more--><\/p>\n<p>Let us consider an example where we have \u2018ul\u2019 which contains multiple \u2018li\u2019 of animals.<\/p>\n<pre class=\"lang:default decode:true \">&lt;ul id='animals'&gt;\r\n    &lt;li id='animal1'&gt;Lion&lt;\/li&gt;\r\n    &lt;li id='animal2'&gt;Tiger&lt;\/li&gt;\r\n    &lt;li id='animal3'&gt;Jaguar&lt;\/li&gt;\r\n    &lt;li id='animal4'&gt;Leopard&lt;\/li&gt;\r\n    &lt;li id='animal5'&gt;Cheetah&lt;\/li&gt;\r\n&lt;\/ul&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p>Now, here we want to perform an action when we click on the animal (li). As a developer first thing we do is adding an event listener to each \u2018li\u2019 and perform whatever action needs to be performed as below.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"git\">document.getElementById('animal1').addEventListener('click',function(){\r\n  console.log('animal1');\r\n});<\/pre>\n<p>There is nothing wrong with above method, it will work awesome <b>but but but<\/b>\u2026. What if list is dynamic, and we need to add or remove some of the animals from the list?<\/p>\n<p>We will do it, and we will also add and remove the list values and their associates event listener. But adding hundreds of event listeners is really a bad idea. This way of adding an event listener will also cause a memory leakage issue and will degrade the performance of your code.<\/p>\n<h4 id=\"whats-the-solution\">What\u2019s the Solution?<\/h4>\n<p>Solution is simple, add an event listener to the parent \u2018ul\u2019. But after adding a listener to the \u2018ul\u2019 how to find which \u2018li\u2019 is clicked?<\/p>\n<p>Again, answer is simple: When event is bubbled up to the \u2018ul\u2019 element, you can check the target property of your object and it will help you to get which \u2018li\u2019 is clicked from the list. If you want to read more about event bubbling and capturing than do visit my previous article here at: <a href=\"https:\/\/code4developers.com\/event-capturing-bubbling-javascript\/\">https:\/\/code4developers.com\/event-capturing-bubbling-javascript\/<\/a><\/p>\n<p>Please consider below code to achieve what we have talked so far.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"git\">document.getElementById(\"animals\").addEventListener(\"click\", function(e) {\r\n  if(e.target &amp;&amp; e.target.nodeName == \"LI\") {\r\n  console.log(e.target.innerText);\r\n }\r\n});<\/pre>\n<p>In above code we are adding event listener to parent element \u2018ui\u2019. When the event will be fired we will check the clicked element is \u2018LI\u2019 which we can check using \u2018<b>e.target.nodeName<\/b>\u2019. If it is \u2018LI\u2019 we are done.<\/p>\n<h4 id=\"summary\">Summary<\/h4>\n<p>Most of the developers uses JavaScript library and frameworks like JQuery, AngularJs for their DOM element and event handling. I recommend all of you to use event delegation methods your library or framework is providing. They provide advanced delegation and element identification.<\/p>\n<h3 id=\"what-to-read-next\">What to read next&#8230;<\/h3>\n<ul>\n<li>\n<h4 id=\"event-capturing-and-bubbling-in-javascript\"><a href=\"https:\/\/code4developers.com\/event-capturing-bubbling-javascript\/\">Event Capturing and bubbling in JavaScript<\/a><\/h4>\n<\/li>\n<li>\n<h4 id=\"whats-new-in-ecmascript-2018\"><a href=\"https:\/\/code4developers.com\/whats-new-ecmascript-2018\/\">What&#8217;s new in ECMASCRIPT 2018?<\/a><\/h4>\n<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Event delegation is a pattern of adding an event listener to a parent node instead, of adding an event listener to the individual node. The added event listener will check&hellip;<\/p>\n","protected":false},"author":4,"featured_media":3127,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[2],"tags":[159,43,22],"powerkit_post_featured":[],"class_list":{"0":"post-3468","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"tag-event-delegation","9":"tag-event-handling","10":"tag-javascript"},"jetpack_featured_media_url":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8NAi4-TW","jetpack-related-posts":[{"id":2975,"url":"https:\/\/code4developers.com\/event-capturing-bubbling-javascript\/","url_meta":{"origin":3468,"position":0},"title":"Event Capturing and Bubbling in JavaScript","author":"Yatendrasinh Joddha","date":"July 21, 2017","format":false,"excerpt":"The DOM has two approaches for object to sense events: first is top down approach and second is bottom up approach. Top down approach is called event capturing\u00a0whereas bottom up is known as event bubbling. Let\u2019s start with example where you have one html which contains <div>, <p> under <div>,\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":14686,"url":"https:\/\/code4developers.com\/unlocking-the-power-of-react-hooks\/","url_meta":{"origin":3468,"position":1},"title":"Unlocking the Power of React Hooks: A Comprehensive Guide with Examples","author":"Yatendrasinh Joddha","date":"October 15, 2023","format":false,"excerpt":"In the ever-evolving world of web development, React has been a game-changer. It simplifies building interactive and dynamic user interfaces. With React, you can create components, manage states, and handle side effects seamlessly. But as React evolves, so do the best practices and techniques for building applications. One significant improvement\u2026","rel":"","context":"In &quot;React&quot;","block_context":{"text":"React","link":"https:\/\/code4developers.com\/category\/react\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2023\/10\/React-icon.svg_-1-e1697396875978.png?fit=250%2C217&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":3818,"url":"https:\/\/code4developers.com\/slicepipe-jsonpipe-asyncpipe\/","url_meta":{"origin":3468,"position":2},"title":"Pipes in Angular Part \u2013 4 : SlicePipe, JSONPipe, AsyncPipe","author":"Yatendrasinh Joddha","date":"August 19, 2018","format":false,"excerpt":"Here is the fourth part of angular pipe series in this part we will discuss about SlicePipe, JSONPipe, and AsyncPipe. If you have not read previous articles here is the link for previous articles. Pipes in Angular Part \u2013 1 : lowercase, uppercase, and titlecase pipes Pipes in Angular Part\u2026","rel":"","context":"In &quot;Angular&quot;","block_context":{"text":"Angular","link":"https:\/\/code4developers.com\/category\/angular\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/06\/angular-2.png?fit=240%2C240&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":3544,"url":"https:\/\/code4developers.com\/angular-6-crud-part-1-project-setup-routing-service\/","url_meta":{"origin":3468,"position":3},"title":"Angular 6 CRUD \u2013 Part 1: Project Setup, Routing, Service","author":"Nisarg Dave","date":"May 9, 2018","format":false,"excerpt":"This article is Part 1 Angular 6 CRUD. In this article and upcoming article, we will discuss performing CRUD operations in Angular 6 i.e. Creating, Reading, Updating and Deleting in Angular 6 with simple examples. We will also discuss about the Angular 6 Project setup, apply Routing, create service to\u2026","rel":"","context":"In &quot;Angular&quot;","block_context":{"text":"Angular","link":"https:\/\/code4developers.com\/category\/angular\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2018\/05\/json-server-call-300x297.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":4091,"url":"https:\/\/code4developers.com\/create-custom-pipes-aka-filters-in-angular-2-x\/","url_meta":{"origin":3468,"position":4},"title":"Create Custom Pipes &#8211; Filters in Angular 2.X +","author":"Arif Khoja","date":"March 10, 2019","format":false,"excerpt":"Our applications may have a lot of data for presentation, But for creating a good user experience it is preferable to see in a more understandable format like March 12, 2010 is better to read then Mon Mar 12 2010 15:23:40 GMT-0700 (Pacific Daylight Time). For such small and repeated\u2026","rel":"","context":"In &quot;Angular&quot;","block_context":{"text":"Angular","link":"https:\/\/code4developers.com\/category\/angular\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/06\/angular-2.png?fit=240%2C240&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":3194,"url":"https:\/\/code4developers.com\/react-hello-world-and-jsx\/","url_meta":{"origin":3468,"position":5},"title":"React: Hello World and JSX","author":"Arif Khoja","date":"January 8, 2018","format":false,"excerpt":"This is a typical Hello World implementation in React in JSX file. It shows one of two ways you can write components, and how you pass data to a components. import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class App extends Component { render() { return (\u2026","rel":"","context":"In &quot;React&quot;","block_context":{"text":"React","link":"https:\/\/code4developers.com\/category\/react\/"},"img":{"alt_text":"react","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/12\/react_2.png?fit=375%2C375&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3468","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/comments?post=3468"}],"version-history":[{"count":8,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3468\/revisions"}],"predecessor-version":[{"id":3573,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3468\/revisions\/3573"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media\/3127"}],"wp:attachment":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media?parent=3468"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/categories?post=3468"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/tags?post=3468"},{"taxonomy":"powerkit_post_featured","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/powerkit_post_featured?post=3468"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}