JSFiddle - React, Tailwind, and code Playground

by superyngo

HTML

<body>
    <div class="container">
      <button class="prev">&#10094;</button>
      <button class="next">&#10095;</button>
      <img class="carousel" />
    </div>
  </body>

CSS

*,
*::before,
*::after {
  box-sizing: border-box;
}

img,
picture,
svg,
video {
  display: block;
}

* {
  margin: 0;
  padding: 0;
  font: inherited;
}

html {
  color-scheme: dark light;
}

body {
  min-height: 100svh;
  position: relative;
}

.container {
  width: 100svw;
  height: 100svh;
  border: 5px solid lightgray;
  background-color: blanchedalmond;
  overflow: hidden;
}

button {
  position: absolute;
  top: 50svh;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 3rem;
  color: rgba(255, 255, 255, 0.5);
  z-index: 2;
  cursor: pointer;
  border-radius: 5px;
  width: 3rem;
  margin: 5px;
  background-color: rgba(0, 0, 0, 0.1);
}

button:hover,
button:focus {
  background-color: rgba(0, 0, 0, 0.3);
}

button.next {
  right: 0;
}

img {
  inset: 0;
  visibility: visible;
  opacity: 1;
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
  transition: opacity 0.5s;
  /* transition-delay: 0.2s; */
}

img.hide {
  opacity: 0;

}

JavaScript

const btns = document.querySelectorAll("button");
const imgs = [
  "https://plus.unsplash.com/premium_photo-1674815846758-5423378481b5?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80",
  "https://images.unsplash.com/photo-1678806525080-a3ef276e954d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
  "https://images.unsplash.com/photo-1678710194874-af547ceac289?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80",
  "https://images.unsplash.com/photo-1678802071553-f14c43e40002?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2564&q=80",
  "https://images.unsplash.com/photo-1678816252761-e77f87def9d7?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
];
let imgIndex = 0;
const img = document.querySelector("img.carousel");
img.src = imgs[imgIndex];

for (let btn of btns) {
  btn.addEventListener("click", function () {
    const offset = btn.className.includes("next") ? 1 : -1;
    imgIndex = imgIndex + offset;
    if (imgIndex > imgs.length - 1) {
      imgIndex = 0;
    }
    if (imgIndex < 0) {
      imgIndex = imgs.length - 1;
    }
    img.classList.add("hide");
    img.addEventListener("transitionend", function () {
      img.src = imgs[imgIndex];
      img.classList.remove("hide");
    });
  });
}