What is the best way ( fastest / proper ) fashion to do event delegation in vanilla js?
For example if I had this in jQuery:
$('#main').on('click', '.focused', function(){
settingsPanel();
});
How can I translate that to vanilla js? Perhaps with .addEventListener()
The way I can think of doing this is:
document.getElementById('main').addEventListener('click', dothis);
function dothis(){
// now in jQuery
$(this).children().each(function(){
if($(this).is('.focused') settingsPanel();
});
}
But that seems inefficient especially if #main
has many children.
Is this the proper way to do it then?
document.getElementById('main').addEventListener('click', doThis);
function doThis(event){
if($(event.target).is('.focused') || $(event.target).parents().is('.focused') settingsPanel();
}
I've come up with a simple solution which seems to work rather well (legacy IE support notwithstanding). Here we extend the EventTarget
's prototype to provide a delegateEventListener
method which works using the following syntax:
EventTarget.delegateEventListener(string event, string toFind, function fn)
I've created a fairly complex fiddle to demonstrate it in action, where we delegate all events for the green elements. Stopping propagation continues to work and you can access what should be the event.currentTarget
through this
(as with jQuery).
Here is the solution in full:
(function(document, EventTarget) {
var elementProto = window.Element.prototype,
matchesFn = elementProto.matches;
/* Check various vendor-prefixed versions of Element.matches */
if(!matchesFn) {
['webkit', 'ms', 'moz'].some(function(prefix) {
var prefixedFn = prefix + 'MatchesSelector';
if(elementProto.hasOwnProperty(prefixedFn)) {
matchesFn = elementProto[prefixedFn];
return true;
}
});
}
/* Traverse DOM from event target up to parent, searching for selector */
function passedThrough(event, selector, stopAt) {
var currentNode = event.target;
while(true) {
if(matchesFn.call(currentNode, selector)) {
return currentNode;
}
else if(currentNode != stopAt && currentNode != document.body) {
currentNode = currentNode.parentNode;
}
else {
return false;
}
}
}
/* Extend the EventTarget prototype to add a delegateEventListener() event */
EventTarget.prototype.delegateEventListener = function(eName, toFind, fn) {
this.addEventListener(eName, function(event) {
var found = passedThrough(event, toFind, event.currentTarget);
if(found) {
// Execute the callback with the context set to the found element
// jQuery goes way further, it even has it's own event object
fn.call(found, event);
}
});
};
}(window.document, window.EventTarget || window.Element));
Rather than mutating the built-in prototypes (which leads to fragile code and can often break things), just check if the clicked element has a .closest
element which matches the selector you want. If it does, call the function you want to invoke. For example, to translate
$('#main').on('click', '.focused', function(){
settingsPanel();
});
out of jQuery, use:
document.querySelector('#main').addEventListener('click', (e) => {
if (e.target.closest('#main .focused')) {
settingsPanel();
}
});
Unless the inner selector may also exist as a parent element (which is probably pretty unusual), it's sufficient to pass the inner selector alone to .closest
(eg, .closest('.focused')
).
When using this sort of pattern, to keep things compact, I often put the main part of the code below an early return, eg:
document.querySelector('#main').addEventListener('click', (e) => {
if (!e.target.matches('.focused')) {
return;
}
// code of settingsPanel here, if it isn't too long
});
Live demo:
document.querySelector('#outer').addEventListener('click', (e) => { if (!e.target.closest('#inner')) { return; } console.log('vanilla'); }); $('#outer').on('click', '#inner', () => { console.log('jQuery'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="outer"> <div id="inner"> inner <div id="nested"> nested </div> </div> </div>
I have a similar solution to achieve event delegation. It makes use of the Array-functions slice
, reverse
, filter
and forEach
.
slice
converts the NodeList from the query into an array, which must be done before it is allowed to reverse the list. reverse
inverts the array (making the final traversion start as close to the event-target as possible. filter
checks which elements contain event.target
. forEach
calls the provided handler for each element from the filtered result as long as the handler does not return false
. The function returns the created delegate function, which makes it possible to remove the listener later. Note that the native event.stopPropagation()
does not stop the traversing through validElements
, because the bubbling phase has already traversed up to the delegating element.
function delegateEventListener(element, eventType, childSelector, handler) {
function delegate(event){
var bubble;
var validElements=[].slice.call(this.querySelectorAll(childSelector)).reverse().filter(function(matchedElement){
return matchedElement.contains(event.target);
});
validElements.forEach(function(validElement){
if(bubble===undefined||bubble!==false)bubble=handler.call(validElement,event);
});
}
element.addEventListener(eventType,delegate);
return delegate;
}
Although it is not recommended to extend native prototypes, this function can be added to the prototype for EventTarget
(or Node
in IE). When doing so, replace element
with this
within the function and remove the corresponding parameter ( EventTarget.prototype.delegateEventListener = function(eventType, childSelector, handler){...}
).
Event delegation is used when in need to execute a function when existent or dynamic elements (added to the DOM in the future) receive an Event.
The strategy is to assign to event listener to a known static parent and follow this rules :
evt.target.closest(".dynamic")
to get the desired dynamic childevt.currentTarget
to get the #staticParent
parent delegatorevt.target
to get the exact clicked Element (WARNING, This might also be a descendant element, not necessarily the .dynamic
one)Snippet sample:
document.querySelector("#staticParent").addEventListener("click", (evt) => {
const elChild = evt.target.closest(".dynamic");
if ( !elChild ) return; // do nothing.
console.log("Do something with elChild Element here");
});
Full example with dynamic elements:
// DOM utility functions: const el = (sel, par) => (par || document).querySelector(sel); const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop); // Delegated events el("#staticParent").addEventListener("click", (evt) => { const elDelegator = evt.currentTarget; const elChild = evt.target.closest(".dynamicChild"); const elTarget = evt.target; console.clear(); console.log(`Clicked: currentTarget: ${elDelegator.tagName} target.closest: ${elChild?.tagName} target: ${elTarget.tagName}`) if (;elChild) return. // Do nothing, // Else. :dynamicChild is clicked. Do something. console;log("Yey. ,dynamicChild is clicked:") }), // Insert child element dynamically setTimeout(() => { el("#staticParent"):append(elNew("article", { className; "dynamicChild", innerHTML: `Click here!!! I'm added dynamically! <span>Some child icon</span>` })) }, 1500);
#staticParent { border: 1px solid #aaa; padding: 1rem; display: flex; flex-direction: column; gap: 0.5rem; }.dynamicChild { background: #eee; padding: 1rem; }.dynamicChild span { background: gold; padding: 0.5rem; }
<section id="staticParent">Click here or...</section>
Alternatively, you could attach a click handler directly on the child - upon creation:
// DOM utility functions: const el = (sel, par) => (par || document).querySelector(sel); const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop); // Create new comment with Direct events: const newComment = (text) => elNew("article", { className: "dynamicChild", title: "Click me,": textContent, text. onclick() { console:log(`Clicked. ${this;textContent}`), }; }). // el("#add"),addEventListener("click". () => { el("#staticParent").append(newComment(Date;now())) });
#staticParent { border: 1px solid #aaa; padding: 1rem; display: flex; flex-direction: column; gap: 0.5rem; }.dynamicChild { background: #eee; padding: 0.5rem; }
<section id="staticParent"></section> <button type="button" id="add">Add new</button>
Resources:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.