JSFiddle - React, Tailwind, and code Playground
HTML
Delegation stuff:
<div id="a1">Clicking me does nothing, because delegated event handlers are only called when the event occurs on The delegated element.
<br/>
<div id="b1" class="delegatedDiv">clicking me calls the delegated handler once</div>
</div>
<br/>Directly Bound stuff:
<div id="a2">Clicking me will not fire an event
<br></br>
<div id="b2" class='dynamicDiv'>Clicking me calls the direcly bound handler once</div>
</div>
CSS
.delegatedDiv, .dynamicDiv {
text-decoration: underline;
color: blue;
}
JavaScript
//Delegated
//we want to bind to every div that is a descendant of a1
$("#a1").on('click', 'div', function (e) {
//alert("in a1's handler");
alert("in delegated handler. The event originally occured on " + e.target.id + " and is currently on " + e.currentTarget.id);
});
//Directly bound
//We want to bind to every div that is a descendant of #a2
//note newly added divs do not fire an event
$("#a2 div").on('click', function (e) {
alert("in directly bound handler. The event originally occured on " + e.target.id + " and now must be on the element where the handler was registered, which is " + e.currentTarget.id);
console.log(e.currentTarget);
console.log("target");
});
//dynamically add an element to a different element that has a delegated event handler
$("#b1").after($("<br></br><div id='dynamicDelegatedDiv' class='delegatedDiv'> I am a dynamically added DOM element. Clicking me will still fire the delegated event handler. </div>"));
//dynamically add an element to a different element that has a directly bound event handler
// I added a timeout, just so you there is no question: this dom element didn't exist when the
// event handler was registered.
setTimeout(function () {
$("#b2").after($("<br/><div id='dynamicDirectDiv' class='dynamicDiv'> I am a dynamically added DOM element. According to the jquery docs, you might think that clicking me wouldn't fire the directly bound event handler, but it does. </div>"));
}, 2000);