Elementor Autoplay Carousel Only When In the Viewport

Elementor Autoplay Carousel Only When In the Viewport

First, add the Elementor Autoplay Carousel Only When In the Viewport code to your project

If you want to apply this across multiple pages, paste the code below into an Elementor Custom Code snippet. For a single page, you can paste it into an HTML element (ideally placed near the carousel) on that specific page.

				
					<script>
/* Code from https://element.how/elementor-vertical-fade-justified-carousel/
* Copyright 2024 Element.How
* Licensed for personal and client use for Element.How free and paid users
* No redistribution or resale permitted
*/
window.addEventListener('load', function () {
    let swiperElement = document.querySelector('.autoplayInView .swiper, .autoplayInView .swiper-container');
    let flag = 0;
    let interval = setInterval(() => {
        try {
            flag++;
            if ((swiperElement && swiperElement.swiper.initialized) || flag > 30) {
                initSwiperActions();
                clearInterval(interval);
                if (flag > 30) console.log('Swiper not found');
            }
        } catch (error) {
            console.log(error);
        }
    }, 100);
});


function initSwiperActions() {
    if (document.querySelector('.elementor-editor-active')) return;
    let swiperElement = document.querySelector('.autoplayInView .swiper, .autoplayInView .swiper-container');
    if (!swiperElement || !swiperElement.swiper) return;

    swiperElement.swiper.autoplay.stop();
    swiperElement.swiper.params.loop? swiperElement.swiper.slideToLoop(0) : swiperElement.swiper.slideTo(0);

    /* Resume autoplay when the swiper gets in the viewport */
    let observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                swiperElement.swiper.autoplay.start();
            } else {
                swiperElement.swiper.autoplay.stop(); /* keep this line to stop autoplaying when the carousel goes outside the viewport again, otherwise delete */
            }
        });
    }, { threshold: 0, rootMargin: '0px 0px -30% 0px' });

    observer.observe(swiperElement);
}

</script>

				
			
Now, add a class name to the autoplaying carousel Assign the class name autoplayInView to all the carousels you want to autoplay only when they are visible. You can do this under Advanced > CSS Classes.

Keep autoplaying after starting

The code ensures that carousels autoplay only when they are in the viewport; they will stop when out of view.

To modify this behavior so the carousels continue autoplaying after they start (even if the user scrolls away), remove this line from the code:

swiperElement.swiper.autoplay.stop(); /* Remove this line to keep autoplaying when the carousel is out of the viewport */

Do you need an expert? HIRE US NOW!