<!--
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
-->
<div class="carousel">
  <div class="image-container" id="imgs">
    <img src="https://picsum.photos/id/1015/500/500" alt="pic1" width="500px" height="500px">
    <img src="https://picsum.photos/id/1016/500/500" alt="pic2" width="500px" height="500px">
    <img src="https://picsum.photos/id/1018/500/500" alt="pic3" width="500px" height="500px">
    <img src="https://picsum.photos/id/1019/500/500" alt="pic4" width="500px" height="500px">
    <img src="https://picsum.photos/id/1021/500/500" alt="pic5" width="500px" height="500px">
  </div>
  <div class="button-container">
    <button id=" button-prev" class="btn">Previous</button>
    <button id="button-next" class="btn">Next</button>
  </div>
</div>
/*
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
*/

.carousel {
  display: flex;
  flex-direction: column;
  width: 520px;
  margin: auto;
}
.image-container {
  display: flex;
  margin: auto;
  border: 10px solid red;
  width: 500px;
  height: 500px;
  overflow: hidden;
}
.button-container {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
}
.image-container img {
  transition: 0.3s ease;
}
/*
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
*/

const imgs = document.getElementById("imgs");
const btnPrev = document.getElementById("button-prev");
const btnNext = document.getElementById("button-next");
const slides = document.querySelectorAll(".image-container img");
let index = 0;

const slider = () => {
  if (index > slides.length - 2) {
    index = 0;
  } else {
    index++;
  }

  slides.forEach((slide) => {
    slide.style.transform = `translateX(${-index * 500}px)`;
  });
};
const interval = setInterval(slider, 3000);

slider();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.