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×banks (ツ) (@thomasxbanks) on CodePen.
Top comments (0)