JSFiddle - React, Tailwind, and code Playground
by Clint
HTML
<div id="log">
</div>
<section>
<div data-attr="0">One</div>
<div data-attr="1">Two</div>
<div data-attr="2">Three</div>
</section>
CSS
.active {
background-color: black;
color: white;
}
#log {
padding-bottom: 2rem;
}
section {
padding: 1rem;
border: 1px solid black;
}
section div {
border: 1px solid whitesmoke;
display: inline-block;
cursor: pointer;
user-select: none;
padding: 1rem;
}
JavaScript
function handle(e) {
const attr = e.target.getAttribute('data-attr');
// If there's no data-attr, the event didn't come from a child DIV but the SECTION. Igore these.
if (attr == null) return;
document.getElementById('log').innerText = ` ${e.type} fired with target ${attr}`;
// 'Select' DIV if clicked
if (e.type == "pointerup") {
if (!e.target.classList.contains('active')) {
// Remove the 'active' class from any other element
var x = document.getElementsByClassName('active');
for (var withClass of x) withClass.classList.remove('active');
// Add it to the one that's the current event target
e.target.classList.add('active');
}
}
}
// Listen to pointer events that happen within the section
const el = document.querySelector('section');
el.addEventListener("pointerup", handle);
el.addEventListener("pointerdown", handle);
el.addEventListener("pointermove", handle);