Currently, I am developing a basic rotator that cycles through three pieces of advice on a website. My goal is to create a smooth fade in and out effect by adding and removing classes. While testing in the JavaScript debugger, everything runs smoothly as it steps through each call. However, when running the actual code, the transition appears choppy. I believe this happens because the script only focuses on adding the class without ensuring the transition within the class completes fully. I am seeking guidance on how to make sure the script finishes the transition entirely within the class. Below is the JavaScript function:
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");
}
// The function is called using:
setInterval(rotateAdvice, 4000);
Below are the CSS classes used for the transition effects:
.advice {
opacity: 0;
transition: 1s opacity;
}
.advice-show {
opacity: 1;
transition: 1s opacity;
}
.no-display {
display: none;
visibility: hidden;
}