How to move the first element to the end in JavaScript

It’s been years since I last created a carousel for a web site. Fortunately, things are a ton easier than I remember then being back in the day. Many days spent trying to get things just right, only to find that it didn’t work, or worse, didn’t fail gracefully in Internet Explorer.

This go around, I set out to do this with vanilla JavaScript, and things came together nicely. Nearly perfect, except I didn’t like how the transition from the final slide back to the first frame looked. It worked well enough, but it was an abrupt rewind of all of the slides, and I really just wanted it look and behave like the transition between other slides did.

Back of the line

I knew what needed to happen, conceptually. The first slide needed to appear after the final slide, so that the next transition would be the same.

JavaScript makes it really easy to move an element from the first index to the last. There’s a bit more to it in terms of how the CSS looks, but to pull this off all you need to do is this:

const container = document.querySelector('.container');
container.appendChild(container.firstElementChild);
JavaScript

Here’s a working example if you really want to see things in action:

<div class="container">
  <div>one</div>
  <div>two</div>
  <div>three</div>
  <div>four</div>
  <div>five</div>
</div>
<script>
  setInterval(() => {
    const container = document.querySelector('.container');
    container.appendChild(container.firstElementChild);
  }, 1_000)
</script>
JavaScript
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.