Skip to content

Instantly share code, notes, and snippets.

@desinas
Last active June 12, 2023 20:17
Show Gist options
  • Save desinas/3f9aea1317eea217028f4575d042a62d to your computer and use it in GitHub Desktop.
Save desinas/3f9aea1317eea217028f4575d042a62d to your computer and use it in GitHub Desktop.
Avoid too many events & Event Delegation - Working w Browser Events - Udacity FrontENDev
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);
@desinas
Copy link
Author

desinas commented Apr 5, 2018

🌶️ 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