Last active
May 25, 2020 11:40
-
-
Save itsDiwaker/818a07d52b94064793ff907c2159d15b to your computer and use it in GitHub Desktop.
Event delegation snippet
This file contains hidden or 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
/** | |
* 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