I would emulate in pure Javascript the main functionality of jQuery .on( events , selector , data)
method.
For example
$(document).on('click','.button',function() {
console.log("jquery onclick");
});
I thought it was enough make something like this
document.addEventListener('click',function(e) {
if(e.target.className == 'button2') {
console.log("It works");
}
});
However when I have this html structure:
<button class="button2">Hello <span>World</span></button>
my script doesn't works when the click event is triggered on span
element, because e.target
is span
. (I ignore for this question the complexity of elements with multiple class, and crossbrowsers compatibility)
The source of jQuery is not simple to read and I don't understand how it works (because the first piece of code, in jQuery, works with my html structure).
I need this method because my html is dynamic, and buttons with this class are created, deleted and re-created many times. I don't want add listeners every times.
I would avoid, if possible, to include jquery library.
So, I can do this?
Here the jsFiddle for testing.
Update for 2017: current DOM standards like closest
mean this is now much easier.
const addEventForChild = function(parent, eventName, childSelector, cb){
parent.addEventListener(eventName, function(event){
const clickedElement = event.target,
matchingChild = clickedElement.closest(childSelector)
if (matchingChild) cb(matchingChild)
})
};
To use it just:
addEventForChild(parent, 'click', '.child', function(childElement){
console.log('Woo click!', childElement)
})
Here's a jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With