slick
slick copied to clipboard
Start autoplay when in viewport?
A very nice to have option would be that the autoplay waits until the slider is in viewport for the first time.
I know it's not a recent question, but since I'm still using the Slick slider to this day and I have a solution for it, I'll answer the question in case it helps someone else in the future.
example code:
const slickSliderExample = jQuery('#slickSliderExample').slick({
autoplay: false,
autoplaySpeed: 2500,
slidesToShow: 5,
slidesToScroll: 1,
dots: false,
centerMode: true,
focusOnSelect: true,
variableWidth: true,
centerPadding: '0px',
prevArrow: "<button type='button' class='slick-prev'></button>",
nextArrow: "<button type='button' class='slick-next'></button>",
// the magic
responsive: [{
breakpoint: 1200,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
}
}, {
breakpoint: 768,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
variableWidth: true,
centerPadding: '0px'
}
}]
});
// Create an Intersection Observer to detect when the slider is in the viewport
const slickSliderExampleObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// When the slider is in the viewport, start autoplay
slickSliderExample.slick('slickPlay');
} else {
// When the slider is out of the viewport, pause autoplay
slickSliderExample.slick('slickPause');
}
});
});
// Observe the slider element
const slickSliderExampleElement = document.querySelector('#slickSliderExample');
if (slickSliderExampleElement) {
slickSliderExampleObserver.observe(slickSliderExampleElement);
}