r/programminghelp • u/not-the-the • Oct 11 '23
JavaScript How do I DRY up an exponentially growing JS switch/case hell, that adds one class to an element and removes all others, except for one class that always stays there?
Here i have an element named sliderContainer in JS, and a switch/case in an event listener:
switch(currentIndex) {
case 0:
sliderContainer.classList.add('lightred');
sliderContainer.classList.remove('lightblue');
sliderContainer.classList.remove('lightyellow');
break; case 1:
sliderContainer.classList.remove('lightred');
sliderContainer.classList.add('lightblue');
sliderContainer.classList.remove('lightyellow');
break; case 2:
sliderContainer.classList.remove('lightred');
sliderContainer.classList.remove('lightblue');
sliderContainer.classList.add('lightyellow');
break;
}With this code, I'm trying to add a class to an element, while removing any other class from it, except keeping the class .slider-container, such that CSS doesn't break. (Changing slider-container to an ID and only doing shenanigans with classes is a possibility).
As you can see, this code is a candidate for being posted on r/YandereTechnique. How can I clean it up and make it DRY?