Vanilla JS event delegation – dealing with child elements of the target element

Newer browsers Newer browsers support .matches: this.container.addEventListener(‘click’, function(e){ if (e.target.matches(‘#game-again,#game-again *’)) { e.stopPropagation(); self.publish(‘primo:evento’); } }); You can get the unprefixed version with var matches = document.body.matchesSelector || document.body.webkitMatchesSelector || document.body.mozMatchesSelector || document.body.msMatchesSelector || document.body.webkitMatchesSelector And then use .apply for more browsers (Still IE9+). Older browsers Assuming you have to support older browsers, you can … Read more

Native JS equivalent to jQuery delegation

What happens is basically this: // $(document).on(“click”, <selector>, handler) document.addEventListener(“click”, function(e) { for (var target=e.target; target && target!=this; target=target.parentNode) { // loop parent nodes from the target to the delegation node if (target.matches(<selector>)) { handler.call(target, e); break; } } }, false); However, e.currentTarget is document when the handler is called, and e.stop[Immediate]Propagation() will work differently. … Read more

Event delegation vs direct binding when adding complex elements to a page

You will create less CPU overhead in binding the events using $(<root-element>).on(<event>, <selector>) since you will be binding to a single “root” element instead of potentially many more single descendant elements (each bind takes time…). That being said, you will incur more CPU overhead when the actual events occur as they have to bubble up … Read more