Last active
June 12, 2023 20:17
-
-
Save desinas/3f9aea1317eea217028f4575d042a62d to your computer and use it in GitHub Desktop.
Avoid too many events & Event Delegation - Working w Browser Events - Udacity FrontENDev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myCustomDiv = document.createElement('div'); | |
function respondToTheClick(evt) { | |
console.log('A paragraph was clicked: ' + evt.target.textContent); | |
} | |
for (let i = 1; i <= 200; i++) { | |
const newElement = document.createElement('p'); | |
newElement.textContent = 'This is paragraph number ' + i; | |
myCustomDiv.appendChild(newElement); | |
} | |
document.body.appendChild(myCustomDiv); | |
myCustomDiv.addEventListener('click', respondToTheClick); |
🌶️ One of the hot methodologies in the JavaScript world is event delegation, and for good reason. Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements. The base concept is fairly simple but many people don't understand just how event delegation works. Let me explain the how event delegation works and provide pure JavaScript example of basic event delegation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now there is only: a single event listener, a single listener function.
Now the browser doesn't have to store in memory two hundred different event listeners and two hundred different listener functions. That's a great for performance`! However, if you test the code above, you'll notice that we've lost access to the individual paragraphs. There's no way for us to target a specific paragraph element.So how do we combine this efficient code with the access to the individual paragraph items that we did before? We use a process called event delegation.
The event object has a .target property. This property references the target of the event. Remember the capturing, at target, and bubbling phases?...these are coming back into play here, too!
Let's say that you click on a paragraph element. Here's roughly the process that happens:
So event.target gives us direct access to the paragraph element that was clicked. Because we have access to the element directly, we can access its .textContent, modify its styles, update the classes it has - we can do anything we want to it!