Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Created November 12, 2019 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettinternet/8b24616085b0ac89b553b305fdc74a0c to your computer and use it in GitHub Desktop.
Save brettinternet/8b24616085b0ac89b553b305fdc74a0c to your computer and use it in GitHub Desktop.
Event Delegation example

Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM.

The benefits of this technique are:

  • Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant.
  • There is no need to unbind the handler from elements that are removed and to bind the event for new elements.
Resources
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ul onclick="alert(event.type + ' on ' + event.target.innerText)">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment