DEV Community

Cover image for Quick and dirty carousel
Thomas Rigby
Thomas Rigby

Posted on • Originally published at thomasxbanks.com on

3 2

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay