I have a slideshow component that I wrote in javascript using jQuery. The slideshow consists of three slides, each containing HTML content. Each slide is a div with class .slide. Every 7 seconds, I fade out the slides that should be hidden and fade in the one I want to show. I also have some buttons (indicators) that let the user manually switch slides by clicking the buttons.
It all works great, unless the user switches tabs. If enough time elapses, when the user returns, there will be two slides visible. When the switch slide event fires, everything goes back to normal.
Example:
Here is my code:
var slides = $(".slide");
var indicators = $(".indicator li");
var currentSlide = 1;
var incrementSlide = function () {
currentSlide = currentSlide === 2 ? 0 : currentSlide + 1;
};
var switchSlide = function () {
if (currentSlide === 0) {
var onDeck = 1;
var inTheHole = 2;
} else if (currentSlide === 1) {
var onDeck = 2;
var inTheHole = 0;
} else {
var onDeck = 0;
var inTheHole = 1;
}
indicators.removeClass("active");
$(indicators[currentSlide]).addClass("active");
$(slides[onDeck]).hide();
$(slides[inTheHole]).fadeOut(200, function () {
$(slides[currentSlide]).fadeIn(200);
incrementSlide();
});
};
var interval = setInterval(switchSlide, 7000);
indicators.click(function () {
clearInterval(interval);
if ($(this).hasClass("first")) {
currentSlide = 0;
} else if ($(this).hasClass("second")) {
currentSlide = 1;
} else if ($(this).hasClass("third")) {
currentSlide = 2;
}
switchSlide();
interval = setInterval(switchSlide, 7000);
});