DEV Community

Cover image for Quick and dirty carousel
Thomas Rigby
Thomas Rigby

Posted on • Originally published at thomasxbanks.com on

Quick and dirty carousel

One thing I find myself looking up time and time again, is;

How do I move the first item of an array to the end? 🤔

So, in the spirit of If I write it down, I'll never forget it, here's a quick and dirty carousel that does just that.


const duration = 5000

const carousel = document.querySelector('[data-carousel]')

const slides = [...carousel.querySelectorAll('[data-slide]')]

const initCarousel = (carousel, slides) => {
  slides.push(slides.splice(0,1)[0])
  carousel.innerHTML = ''
  carousel.insertAdjacentElement('afterbegin', slides[0])
}

setInterval(() => initCarousel(carousel, slides), duration)

Enter fullscreen mode Exit fullscreen mode

Let's break that down…

First we set the duration, 5000 milliseconds (5 seconds) should be good enough.

const duration = 5000
Enter fullscreen mode Exit fullscreen mode

Next, identify your elements. Your common or garden carousel consists of a container (<div data-carousel /> in this case) and some slides (<article data-slide /> in this case).

const carousel = document.querySelector('[data-carousel]')

const slides = [...carousel.querySelectorAll('[data-slide]')]
Enter fullscreen mode Exit fullscreen mode

Now, here's where the magic happens!

We have a smol function that moves the first item in the array to the end of the array then replaces the entire innerHTML of the container with the first slide in the array.

const initCarousel = (carousel, slides) => {
  slides.push(slides.splice(0,1)[0])
  carousel.innerHTML = ''
  carousel.insertAdjacentElement('afterbegin', slides[0])
}
Enter fullscreen mode Exit fullscreen mode

Finally, we run the function over and over again, every 5 seconds…

setInterval(() => initCarousel(carousel, slides), duration)
Enter fullscreen mode Exit fullscreen mode

Conclusion

And that's it!

OK, sure, it doesn't have any fancy transitions but hopefully I'll remember the magic formula! 🙏

arr.push(arr.splice(0,1)[0])
Enter fullscreen mode Exit fullscreen mode

See the Pen Quick and dirty carousel by thomas×banks (ツ) (@thomasxbanks) on CodePen.

Top comments (0)