Hi all,
I am trying to create a dynamic slider linked to a CMS collection. I found a code snippet that works for the first CMS item, but not the rest (you will see the default ‘background image’.
All CMS items have placeholder images in their multi-image field, so I would expect to see the images appear here.
Below is the code snippet I’m using, and also sharing the read-only and staging links to the site.
Many thanks!
Jordan
(function () {
// Configuration variables
var sliderId = 'MultiImageSlider';
var collectionListWrapperId = 'MultiImageCollectionWrapper';
var slideClass = 'w-slide';
var leftArrowClass = 'w-slider-arrow-left';
var rightArrowClass = 'w-slider-arrow-right';
var slideNavClass = 'w-slider-nav';
var collectionItemClass = 'w-dyn-item';
// Retrieve DOM elements based on the provided IDs and classes
var $slider = $('#' + sliderId);
var $slides = $slider.find('.' + slideClass);
var $collectionWrapper = $('#' + collectionListWrapperId);
var $images = $collectionWrapper.find('.' + collectionItemClass);
// Check if both slider and collection wrapper elements exist
if ($slider && $collectionWrapper) {
// Set the initial opacity of the slider to 0
$slider.css('opacity', 0);
// Check if images exist within the collection
if (!$images || !$images.length) {
// If no images exist, remove the slider element
$slider.remove();
} else {
// Determine the number of images and slides
var imgCount = $images.length;
var slideCount = $slides.length;
// Adjust image count if it exceeds the slide count
if (imgCount > slideCount) imgCount = slideCount;
// Assign background images to slides based on the images in the collection
for (var i = 0; i < imgCount; i++) {
$slides[i].style.backgroundImage = $images[i].style.backgroundImage;
}
// Remove excess slides if the image count is less than the slide count
for (var i = slideCount; i > imgCount; i--) {
$slides[i - 1].remove();
}
// Remove slider navigation and arrows if there is only one image
if (imgCount < 2) {
$slider.find('.' + leftArrowClass + ', .' + rightArrowClass + ', .' + slideNavClass).remove();
}
// Set the opacity of the slider to 1
$slider.css('opacity', 1);
}
// Remove the collection wrapper element
$collectionWrapper.remove();
}
})();
Staging site
https://dean-daughters.webflow.io/