Skip to content

Instantly share code, notes, and snippets.

@itsDiwaker
Last active May 25, 2020 11:40
Show Gist options
  • Save itsDiwaker/818a07d52b94064793ff907c2159d15b to your computer and use it in GitHub Desktop.
Save itsDiwaker/818a07d52b94064793ff907c2159d15b to your computer and use it in GitHub Desktop.
Event delegation snippet
/**
* Based on jQuery $.on API
* Helpful when trying to bind to an element that might get re-renderd in future
* because of some AJAX call or some other DOM manipulation
* that required detaching the element or it's parent from the DOM.
* Saves the extra code to re-attach all the event handlers.
*/
const delegateEvent = (el, evt, sel, handler, useCapture) => {
if(typeof useCapture === 'undefined') {
useCapture = false;
}
el.addEventListener(evt, function(event) {
var t = event.target;
while (t && t !== this) {
if (t.matches(sel)) {
handler.call(t, event);
}
t = t.parentNode;
}
}, useCapture);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment