简体   繁体   中英

loop back to first slide in a slider when user reaches last slide on the carousel

I'm trying to recreate this slider: https://bewegen.com/en its under the Accelerating Bike Share section. I managed to create the count slider but having trouble getting it back to count 1 when it hits the end count of 9 - smoothly have it loop back to the start.

How to get the count to loop back to the start like in the example above?

Here is my codepen work: https://codepen.io/harp30/pen/GYEXXe

Thank you.

You can modify your next() function like this:

function next() {
  count = count + 1;
  if (count > num.length - 1) {
    // Clone first item and add it to the end
    var clone = num[0].cloneNode(true);
    countItemNumberHolder.appendChild(clone);

    // Let the transition happen normally
    TweenMax.to(countItemNumberHolder, 0.4, { y: -289 * count });

    // Wait for transition to finish and reset transform to 0 without animation
    setTimeout(function() {
      TweenMax.to(countItemNumberHolder, 0, { y: 0 });
      countItemNumberHolder.removeChild(clone);
    }, 300);

    // Now reset counter
    count = 0;

  } else {
    TweenMax.to(countItemNumberHolder, 0.4, { y: -289 * count });
  }
}

Essentially, when you reach the last element, clone the first element and let the transition happen normally. Once the transition is complete, reset your transform to 0 without animation, and remove the cloned element. Similarly, you can do the same for the previous button.

However, you will probably want to remove and add the event listeners during the transition, otherwise, if the user clicks rapidly, it might lead to unexpected behavior.

A much cleaner implementation of an infinite carousel can be found here: https://codepen.io/matthewwilliams/pen/Vayrjv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM