Skip to content
people riding carousel during daytime

Quick and dirty carousel

Tuesday, 13 April 2021

At 272 words, this article should take about 1 minute to read.

This article is more than a year old and the information in it may be out of date.

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)

Let's break that down…

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

const duration = 5000

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]')]

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])
}

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

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

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])

See the Pen Quick and dirty carousel by Thomas Rigby (@hryggrbyr) on CodePen.

Cover image courtesy of Mitya Ivanov.


Fin

Comments

In almost all cases, the comments section is a vile cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).

Thomas Rigby

Thomas Rigby

When I'm not building things for the internet, I take photos of stuff.

Pronouns: he/him/his

Real. Simple. Syndication.

Get my latest content in your favorite RSS reader. I use InoReader but you don't have to.

What even is an RSS feed?!

Subscribe

Last played

Burn the Bitch

Ulver || Svidd Neger

Listen
Loading Invisible Visible RSS Navigation Close Arrow Info Online Online