JSFiddle - React, Tailwind, and code Playground
HTML
<div class="cycle green yellow">Я меняю цвет</div>
<div class="cycle green yellow">Я тоже</div>
CSS
div {
padding: 30px;
color: black;
}
.yellow {
background: yellow;
color: green;
}
.green {
background: green;
color: yellow;
}
.blue {
background: blue;
color: white;
}
JavaScript
var arrD = ["yellow", "green", "blue"];
var elems = Array.apply(null, document.querySelectorAll('div'));
elems.forEach(function(el) {
el.timer = cycleClass(el, arrD, 500);
});
document.addEventListener('mousedown', function(e) {
if (elems.indexOf(e.target) != -1) {
clearInterval(e.target.timer);
delete e.target.timer;
}
});
document.addEventListener('mouseup', function() {
elems.forEach(function(el) {
if (!el.timer)
el.timer = cycleClass(el, arrD, 500);
});
});
function cycleClass(element, list, time) {
var i = -1;
var c = element.classList;
for (var n = 0; n < list.length; n++) {
if (c.contains(list[n])) {
if (i != -1) c.remove(list[i]);
i = n;
}
}
return setInterval(function() {
c.remove(list[i++]);
c.add(list[i %= list.length]);
}, time);
}