ganlanyuan / tiny-slider

Vanilla javascript slider for all purposes.
MIT License
5.26k stars 785 forks source link

It is possibile to change the direction after slide reaches the end? #546

Open endcoreCL opened 4 years ago

endcoreCL commented 4 years ago

We want to change the direction of the autoplay after the slide reaches his end.

Example:

The slider has 4 slides (direction forward). If the slider reaches the last (4th) slide, we want to change the direction (autoplayDirection = backwards) to slide backwards (4-3-2-1).

Any ideas? :/

sunixzs commented 4 years ago

Hi @endcoreCL

just an idea: use the transitionEnd event and build own autoplay.

something like this:

var slider = tns({autoplay: false, ...});
var autoplayDirection = "forwards";
var timer = null;

// calculate the beginning and end and pay attention to the direction
let nextStep = () => {
    let info = slider.getInfo();
    if (autoplayDirection === "forwards") {
        if (info.index + 1 <= info.navItems.length + info.items) {
            slider.goTo("next");
        } else {
            slider.goTo("prev");
            autoplayDirection = "backwards";
        }
    } else {
        if (info.index - 1 > 0) {
            slider.goTo("prev");
        } else {
            slider.goTo("next");
            autoplayDirection = "forwards";
        }
    }
};

// listen to the end of a transition, wait and do the next step
slider.events.on("transitionEnd", () => {
  timer = setTimeout(nextStep, 1000);
});

// start play
timer = setTimeout(nextStep, 1000);

Said, it's an idea only and won't work. Not tested or so. The min/max calculation is definitely wrong.
If you have also transport buttons you can add event listener to null the timer to avoid going further: "onPressArrow"clearTimeout(timer)...