Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An infinite carousel with vanilla JavaScript

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.

like image 650
Denis Rozimovschii Avatar asked Sep 24 '16 07:09

Denis Rozimovschii


People also ask

What is infinite carousel?

A timed infinite carousel that uses vanilla JavaScript & CSS animations. It supports both horizontal and vertical scrolling. Useful if you need a UI element to continuously scroll (ex: ticker being displayed on a TV monitor).


1 Answers

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
    }
}
like image 192
Tobi Obeck Avatar answered Sep 27 '22 15:09

Tobi Obeck