Cloning carousel slides with JavaScript

Hi, I am trying to figure out how to build a carousel. And I want to make it start over with a smooth transition and for that, I need to copy the first slide to the back and the last slide to the front.

I managed to clone the slides but I have a few problems.

  1. I can see my elements when I console.log but the user can’t see them. I have 3 slides and with the clones, I should have 5 but that isn’t the case. When I get to the last slide an error fires in the console saying that it can not read the code that moves the track. =‘translateX(-’+ +’)’;

  2. The clones are added last. And when I am trying to push the last slide to the front another error fires that is saying that track.push(lastSlideCopy) is not a function.

  3. I have some weird interaction where the middle slide is too small or the next button and prev button don’t work as they should. Works only 1 of them or prev goes to the last slide and next goes to the first etc. But if I refresh the page everything goes to normal.

Here is the CodePen:

re: 2. There is no “push”. You must use the insertBefore() method, i.e. this:

list.insertBefore(lastSlideCopy, firstSlide);

You won’t need the extra ‘appendChild’ of the lastSlideCopy after using the above.

Things work much better with this corrected.

re: 1. After the above fix, I look at the console.Log(track) results, this is what I see:

Note the first (clone) slide has no “left” style, as does the last (clone). cloneNode is not cloning the style, and thus the error.  This has some more in-depth info which might help your next steps.