slick icon indicating copy to clipboard operation
slick copied to clipboard

Start autoplay when in viewport?

Open slaetthult opened this issue 7 years ago • 1 comments

A very nice to have option would be that the autoplay waits until the slider is in viewport for the first time.

slaetthult avatar Sep 19 '17 12:09 slaetthult

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);
}

ZsoltBenes avatar Oct 16 '23 12:10 ZsoltBenes