I'm building a simple rotator that rotates three pieces of advice for a website. I want it to fade out/in and adding/removing classes to do that. In the JavaScript debugger, it works perfectly, because it is given time to step through all of the calls, but in actual execution, it is very choppy. I understand it's doing that because the script only cares about adding the class, it doesn't care about completing the transition in the class, but I need to know how to get the script to fully finish the transition in the class. Here is the JavaScript:
function rotateAdvice() {
let nextAdvice;
const currentAdviceCont = document.querySelector(".advice-show");
const currentAdvice = currentAdviceCont.id.slice(-1);
if (currentAdvice >= 2) {
nextAdvice = document.getElementById("advice-0");
} else {
nextAdvice = "advice-"+(parseInt(currentAdvice) + 1);
nextAdvice = document.getElementById(nextAdvice);
}
currentAdviceCont.classList.add("advice");
currentAdviceCont.classList.remove("advice-show");
currentAdviceCont.classList.add("no-display");
nextAdvice.classList.remove("no-display");
nextAdvice.classList.add("advice-show");
}
// called through this:
setInterval(rotateAdvice, 4000);
And here are the three css classes:
.advice {
opacity: 0;
transition: 1s opacity;
}
.advice-show {
opacity: 1;
transition: 1s opacity;
}
.no-display {
display: none;
visibility: hidden;
}