JSFiddle - React, Tailwind, and code Playground
HTML
<div class="list">
<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
CSS
.item {
display: inline-block;
margin: 10px;
width: 100px;
height: 100px;
background-color: blue;
}
.active {
background-color: red;
}
JavaScript
class PolySwitch {
constructor(root, delay) {
this.root = root;
this.delay = delay;
this.isRunning = true;
this.eventHandler = this.eventHandler.bind(this);
this.timeout = setTimeout(this.loop.bind(this), this.delay);
this.root.addEventListener("pointerover", this.eventHandler);
this.root.addEventListener("pointerout", this.eventHandler);
this.root.addEventListener("click", this.eventHandler);
}
loop() {
this.setActiveElement();
if(this.isRunning)
this.timeout = setTimeout(this.loop.bind(this), this.delay);
}
eventHandler(event) {
if(event.type === "pointerover") {
this.isRunning = false;
clearTimeout(this.timeout);
}
if(event.type === "pointerout") {
this.isRunning = true;
this.timeout = setTimeout(this.loop.bind(this), this.delay);
}
if(event.type === "click") {
if(event.target.matches(".item"))
this.setActiveElement(event.target);
}
}
setActiveElement(element) {
const active = this.root.querySelector(".item.active");
const next = element || this.root.querySelector(".item.active + .item") || this.root.querySelector(".item");
active.classList.remove("active");
next.classList.add("active");
}
}
new PolySwitch(document.querySelector(".list"), 1000);