I made a simple carousel. When a user clicks the arrow or one of the thumbnails then the main image and one of the thumbnail images swap places.
It worked fine until I tried to change the images to ones with a smaller file size, then nothing worked.
The working carousel is at Personalised Celebration Cakes - The Shhh Baker
The busted carousel is at Test - The Shhh Baker
What confuses me is that when I debug everything it ‘works’ but still nothing happens on the page.
- The script loads
- The clicks on the arrows or thumbnails register
- The image swaps
If I look in inspector, then I can see in the HTML that the image has been swapped to the correct image url, but the old image is still shown if I hover over it.
The first script still works perfectly.
I’ve spent months on this now. Any help much appreciated
document.addEventListener('DOMContentLoaded', () => {// Manually set the image paths
console.log("Carousel script loaded")
let mainImagePath = "https://theshhhbaker.com/wp-content/uploads/2024/08/polly-1-1.webp";
const thumbnailPaths = [
"https://theshhhbaker.com/wp-content/uploads/2024/08/polly-2-1.webp",
"https://theshhhbaker.com/wp-content/uploads/2024/08/polly-3-1.webp"
];
// Get DOM elements
const mainImage = document.getElementById('carousel__main-image');
const thumbnails = document.querySelectorAll('.thumbnail11');
const leftArrow = document.querySelector('.carousel__button--left1');
const rightArrow = document.querySelector('.carousel__button--right1');
let currentIndex = 0;
console.log(mainImage);
console.log(thumbnails);
console.log(leftArrow);
console.log(rightArrow);
// Ensure elements exist before proceeding
if (mainImage && thumbnails.length > 0 && leftArrow && rightArrow) {
// Initialize the images
mainImage.src = mainImagePath;
thumbnails.forEach((thumbnail, index) => {
if (thumbnailPaths[index]) {
thumbnail.src = thumbnailPaths[index];
}
});
console.log("Main image src:", mainImage.src);
// Thumbnail click event
thumbnails.forEach((thumbnail, index) => {
thumbnail.addEventListener('click', () => {
console.log(`Thumbnail ${index} clicked`);
swapImages(index);
currentIndex = index;
console.log("Main image src:", mainImage.src);
});
});
// Arrow click events
leftArrow.addEventListener('click', () => {
console.log("Left arrow clicked");
currentIndex = (currentIndex === 0) ? thumbnails.length - 1 : currentIndex - 1;
swapImages(currentIndex);
console.log("Main image src:", mainImage.src);
});
rightArrow.addEventListener('click', () => {
console.log("Right arrow clicked");
currentIndex = (currentIndex === thumbnails.length - 1) ? 0 : currentIndex + 1;
swapImages(currentIndex);
console.log("Main image src:", mainImage.src);
});
} else {
console.error("Carousel elements not found. Check your HTML structure.");
}
// Function to swap images
function swapImages(index) {
const tempSrc = mainImage.src;
mainImage.src = thumbnails[index].src + `?cache-bust=${Date.now()}`; // cache-busting;
thumbnails[index].src = tempSrc;
}
});