I am working on a Rails application that uses Turbolinks, and I'm encountering an issue with a JavaScript-based slideshow on my pages. The slideshow works fine on the initial page load, but when I navigate away and then return to the page (either by clicking a link with data-turbolinks="false" or using the browser's back button), the slide images stack on top of each other instead of displaying one at a time.
Here is the JavaScript code for my slideshow:
let currentIndex = 0;
const slides = document.querySelectorAll('.slide');
const totalSlides = slides.length;
// Clear any existing intervals
if (window.slideshowInterval) {
clearInterval(window.slideshowInterval);
}
function showSlide(index) {
slides.forEach((slide, idx) => {
slide.style.display = idx === index ? 'block' : 'none';
});
}
function nextSlide() {
currentIndex = (currentIndex + 1) % totalSlides;
showSlide(currentIndex);
}
function prevSlide() {
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
showSlide(currentIndex);
}
// Attach event listeners to arrows for manual control
const leftArrow = document.querySelector('.slideshow-left-arrow');
const rightArrow = document.querySelector('.slideshow-right-arrow');
// Remove existing event listeners to avoid duplicates
leftArrow.removeEventListener('click', prevSlide);
rightArrow.removeEventListener('click', nextSlide);
// Attach new event listeners
leftArrow.addEventListener('click', prevSlide);
rightArrow.addEventListener('click', nextSlide);
// Automatic slideshow - change slide every 3 seconds
window.slideshowInterval = setInterval(nextSlide, 3000);
// Initialize the first slide
showSlide(currentIndex);
}
// Turbolinks event listener
document.addEventListener('turbolinks:load', initializeSlideshow);
I've also attempted the following solutions:
- Clearing and resetting intervals for automatic slide transitions.
- Removing and re-adding event listeners for slide navigation.
- Ensuring idempotent initialization to avoid duplicating event listeners or slideshow elements.
Despite these efforts, the problem still occurs when navigating back to the page with the slideshow. The initial page load works perfectly, but subsequent navigations cause the slides to overlap.
I would greatly appreciate any insights or suggestions on how to resolve this issue, especially any tips on handling JavaScript initialization and event listeners in a Turbolinks environment.
Thank you in advance for your help!