JSFiddle - React, Tailwind, and code Playground
by mitya33
HTML
<div>
<p>I'm a paragraph - click me</p>
</div>
CSS
div { padding: 1rem; border: solid 2px red; background: yellow; }
p { background: cyan; }
JavaScript
window._events = {};
HTMLElement.prototype.on = function(type, selector_or_callback, callback) {
_events[type] = _events[type] || [];
_events[type].push({
el: this,
cb: callback || selector_or_callback,
delSel: !callback ? null : selector_or_callback
});
};
//--------
const evtTypes = ['click', 'input', 'keydown'/* ... */]; //<-- add more types
evtTypes.forEach(type => document.body.addEventListener(type, evt => {
if (!_events[type]) return;
_events[type] && _events[type].forEach(def => {
if (
(evt.target == def.el || [...def.el.querySelectorAll('*')].includes(evt.target)) &&
(!def.delSel || evt.target.matches(def.delSel))
)
def.cb.call(evt.target, evt);
});
}));
//--------
let div = document.querySelector('div');
div.on('click', evt => alert('direct event to div'));
div.on('click', 'p', evt => alert('delegated event to paragraph'));