carousel UI

by dfg312546

HTML

<div class="slideshow">
  <img id="image" src="" alt="Image">
  <button id="prevBtn">&#10094;</button>
  <button id="nextBtn">&#10095;</button>
</div>

CSS

* {
  margin: 0;
  padding: 0;
}

.slideshow {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  height: 100vh;
  overflow: hidden;
}

#image {
  max-width: 100%;
  height: auto;
  overflow: hidden;
}

#prevBtn,
#nextBtn {
  width:30px;
  height:30px;
  border-radius:5px;
  border:none;
  background-color: rgba(255, 255, 255, 0.5);
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

#prevBtn,
#nextBtn:hover {
  cursor: pointer;
}

#prevBtn {
  left: 10px;
}

#nextBtn {
  right: 10px;
}

JavaScript

const imgs = [
  'https://images.unsplash.com/photo-1668680778913-a0a07312ca9a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80',
  'https://images.unsplash.com/photo-1500881263786-ad74c00b9e60?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80',
  'https://images.unsplash.com/photo-1668680765230-95cf8e1dae58?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80',
  'https://plus.unsplash.com/premium_photo-1675756583672-04a27dfe1f64?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80',
  'https://images.unsplash.com/photo-1672512262424-0fa09b244bbc?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=869&q=80'
];

const image = document.getElementById('image');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
let currentImageIndex = 0;

function showImage(index) {
  image.src = imgs[index];
}

prevBtn.addEventListener('click', () => {
  currentImageIndex--;
  if (currentImageIndex < 0) {
    currentImageIndex = imgs.length - 1;
  }
  showImage(currentImageIndex);
});

nextBtn.addEventListener('click', () => {
  currentImageIndex++;
  if (currentImageIndex >= imgs.length) {
    currentImageIndex = 0;
  }
  showImage(currentImageIndex);
});

showImage(currentImageIndex);