How to start autoplay when an element enters the viewport in slick.js

2020年2月8日

I will show you how to start autoplay when an element enters the browser screen (viewport) with slick.js of jQuery plugin.

How to do it

By default, set the option to autoplay: true; and run slick (‘slickPause’).

slickPause

Code sample

$(function () { 

// setting for slick.js
$('#yourTargetCarousel').slick({
    infinite: true,
    slidesToShow: 2,
    slidesToScroll: 2,
    dots: true,
    autoplay: true,
    autoplaySpeed: 3000,
    speed: 1500,
    responsive: [
        {
            breakpoint: 767,
            settings: {
                 slidesToShow: 1,
                 slidesToScroll: 1,
               }
         }
    ]
}).slick('slickPause');

// A function that start autoplay when entering the viewport
function triggerScroll(targetObj) {
    let targetName = targetObj.attr("id"); //for console.log
    let targetFlag = false;
    let scrollTop = $(window).scrollTop();
    let scrollBottom = scrollTop + $(window).height();
    let targetTop = targetObj.offset().top;
    let targetBottom = targetTop + targetObj.height();
   // while loading
    if (scrollBottom > targetTop && scrollTop < targetBottom) {
        if (!targetFlag) {
            console.log(targetName + ' is in sight'); //for console.log
            targetObj.slick('slickPlay');
            targetFlag = true;
        }
    } else {
            console.log(targetName + ' is not in sight'); //for console.log
            targetObj.slick('slickPause');
            targetFlag = false;
    }

    $(window).on('scroll', function () {
        scrollTop = $(window).scrollTop();
        scrollBottom = scrollTop + $(window).height();
        targetTop = targetObj.offset().top;
        targetBottom = targetTop + targetObj.height();
        if (scrollBottom > targetTop && scrollTop < targetBottom) {
            // Start autoplay when entering the viewport
            if (!targetFlag) {
                console.log(targetName + ' is in sight');//確認用
                targetObj.slick('slickPlay');
                targetFlag = true;
            }
        } else {
            // Stop autoplay when you get out of the viewport
            if (targetFlag) {
                console.log(targetName + ' is not in sight');//for console.log
                targetObj.slick('slickPause');
                targetFlag = false;
            }
         }
     });
   }
     // Execute function
   triggerScroll($('#yourTargetCarousel'));
});

additional information

If you want to change other values according to the trigger, use the method “slickSetOption”.

slickSetOption