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)
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.
Fin
Cover image courtesy of Mitya Ivanov.
onward-journeys module
Real. Simple. Syndication.
Get my latest content in your favorite RSS reader.
I use InoReader but you don't have to.
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).