Let's say you have 4 elements and only one of them can have class active. The active element is updated a few times per second (here it's a dummy example in the snippet).
A naive way is to do:
- remove
activefrom every element - set
activeto the currently chosen element
The problem is that if the chosen element hasn't changed, we are removing the class, and resetting it again (which can cause display glitch), which is useless.
Of course we could add another rule to not remove if it's still the chosen one, but the code would become less readable.
Question: is there a standard pattern to do this?
var i = 0;
setInterval(() => {
i += 1;
document.querySelectorAll('.active').forEach(item => item.classList.remove('active'));
document.querySelector('#item' + Math.floor(i /4)).classList.add('active');
}, 500);
.active { color: red; }
<div id="item0" class="active">item 0</div>
<div id="item1">item 1</div>
<div id="item2">item 2</div>
<div id="item3">item 3</div>