An infinite carousel with vanilla JavaScript

Denis Rozimovschii picture Denis Rozimovschii · Sep 24, 2016 · Viewed 15.5k times · Source

I am trying to build my own carousel with pure JavaScript.

I'm struggling with picking up the most efficient way to add an infinite carousel option.

For some reasons, every element (photo, generic object) must have an id

The algorithm I see goes like that:

  • You check if the carousel is overflown (the are enough objects to fit the whole container)
  • If not: append to the back a copy of the first element, then a copy of the second element and so on. (But there will be an issue with the ids, because this object will have the same id)

Adding copies - If the user is scrolling to the last object (to right) then append the first DOM object to the array back
- If the user is scrolling to the first object (to left) then add the last DOM child to array front.

Is this going to work? Is there any other efficient way of doing an infinite carousel?

I have also heard that it's better to use translate property rather than changing the left, right properties, so it there would be more work for the GPU than for CPU.

Answer

Tobi Obeck picture Tobi Obeck · Sep 24, 2016

I created a simple slider with css transformations as the animation technique and plain Javascript.

var img = document.getElementsByClassName("img")[0]; 
img.style.transform = 'translate('+value+'px)';

You can test it in this codepen snippet. http://codepen.io/TobiObeck/pen/QKpaBr

A press on a button translates all images in the respective direction along the x-axis. An image on the edge, is set transparent outerImg.style.opacity = '0'; and translated to the other side. You can add or remove image elements in HTML and it still works.

In this second codepen snippet you can see how it works. The opacity is set to 0.5 so it is observable which image switches the side. Because overflow: hidden is removed, you can see how the images on the edge enqueue on the other side. http://codepen.io/TobiObeck/pen/WGpdLE

Moreover it is notworthy that it is checked wether the animation is complete, otherwise the simultaneously added translations would look odd. Therefore a click won't trigger another animation until unless the animation is completed.

img.addEventListener("transitionend", transitionCompleted, true);

var transitionCompleted = function(){
    translationComplete = true;
}

leftBtnCLicked(){
    if(translationComplete === true){
       //doAnimation
    }
}