JSFiddle - React, Tailwind, and code Playground
by ianclark001
HTML
<script src="https://rawgit.com/evenicoulddoit/9769f78e9a6f359c4561/raw/2a72815257898e9c7edcce31ac65a69edcb2f9eb/js-delegate.js"></script>
<div id="foo">
foo
<div id="bar">
bar
<div id="zulu">
zulu
</div>
</div>
</div>
CSS
body {
color: #333;
font-family: Helvetica;
}
div {
padding: 10px 20px;
background-color: rgba(0, 0, 0, 0.04);
}
#zulu > div:nth-child(2n) {
background-color: rgba(0, 255, 0, 0.02);
}
span {
margin-left: 20px;
}
span:before {
content: "(";
}
span:after {
content: ")";
}
}
JavaScript
/**
* Testing our simple event delegation method
*/
var foo = document.getElementById("foo"),
bar = document.getElementById("bar"),
zulu = document.getElementById("zulu"),
children = 20, elm, i;
// Establish our delegated event
bar.delegateEventListener("click", "#zulu > div:nth-child(2n)", function(e) {
var clicks = parseInt(this.getAttribute("data-clicks")), span;
if(!clicks) {
clicks = 0;
span = document.createElement("span");
this.appendChild(span);
}
else {
span = this.children[0];
}
this.setAttribute("data-clicks", clicks + 1);
span.textContent = this.getAttribute("data-clicks");
e.stopPropagation();
});
// Create another event on a parent which should not run
// when our above event fires (due to stopPropagation)
foo.addEventListener("click", function() {
console.log("Click reached foo");
});
// Create some sought after elements
for(i = 0; i < children; i ++) {
elm = document.createElement("div");
elm.textContent = "element " + i;
zulu.appendChild(elm);
}