pawelgrzybek / siema

Siema - Lightweight and simple carousel in pure JavaScript
https://pawelgrzybek.github.io/siema/
Other
3.48k stars 408 forks source link

Pause autoplay when carousel is not within the viewport #273

Closed patrulea closed 4 years ago

patrulea commented 4 years ago

My current Siema setup changes the slides automatically every 2 seconds, but stops when the user interacts with the carousel (either by sliding or by pressing the slide controls). It’s been working great. A live demo can be seen on my website.

Though, I’d like the autoplay only when the carousel is visible.

This is my current code:

// SIEMA

const mySiema = new Siema({
    duration: 250,
    loop: true,
    easing: "cubic-bezier(.42,0,.58,1)",
    onInit: printSlideIndexWithIndicator,
    onChange: printSlideIndexWithIndicator,
});

// INDICATORS

function printSlideIndexWithIndicator() {
    let currentSlide = this.currentSlide;
    let currentSelector = document.querySelector('.siema-current');
    let totalSelector = document.querySelector('.siema-total');
    /*let zoomSelector = document.querySelector('.siema-zoom');*/
    if (currentSlide < 0) {
        currentSelector.innerHTML = this.innerElements.length + currentSlide + 1;
    } else {
        currentSelector.innerHTML = this.currentSlide + 1;
    }
    totalSelector.innerHTML = this.innerElements.length;
}

// AUTOPLAY

const myInterval = setInterval(() => mySiema.next(), 2000);

document.querySelector(".siema-prev").addEventListener("click", () => {
    mySiema.prev();
    clearInterval(myInterval);
});
document.querySelector(".siema-next").addEventListener("click", () => {
    mySiema.next();
    clearInterval(myInterval);
});
document.querySelector(".siema").addEventListener("mousedown", () => {
    clearInterval(myInterval);
});
document.querySelector(".siema").addEventListener("touchstart", () => {
    clearInterval(myInterval);
});

I’m thinking this could be done by letting the interval run just when the div.siema is within the viewport; though, I know nothing about JavaScript and would be grateful if someone helped me out with this.

pawelgrzybek commented 4 years ago

Hi.

Please look into something like Intersection Observer. I have an article about the subject: https://pawelgrzybek.com/the-intersection-observer-api-explained/

API to detect if a tab / window is active or not that may be helpful is Page Visibility API: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

Hopefully those references are helpful. Have a good day 🥑