Site icon MTZ – My Techno Zone

Create a simple image thumbnail carousel

We can create a simple image thumbnail carousel using HTML, CSS, and Javascript. You can use this code to create a simple image carousel. In this tutorial, we’ll walk through the process of building a basic image thumbnail carousel using HTML, CSS, and JavaScript.

Here is the HTML code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Thumbnail Carousel</title>
</head>
<body>

<div class="carousel-container">
  <div class="carousel-wrapper">
    <div class="carousel">
      <img src="https://picsum.photos/id/1/200/300" alt="Image 1">
      <img src="https://picsum.photos/id/2/200/300" alt="Image 2">
      <img src="https://picsum.photos/id/3/200/300" alt="Image 3">
      <img src="https://picsum.photos/id/4/200/300" alt="Image 4">
      <img src="https://picsum.photos/id/5/200/300" alt="Image 5">
      <img src="https://picsum.photos/id/6/200/300" alt="Image 6">
      <img src="https://picsum.photos/id/7/200/300" alt="Image 7">
     
    </div>
  </div>
  <button class="prev" onclick="moveSlide(-1)">&#10094;</button>
  <button class="next" onclick="moveSlide(1)">&#10095;</button>
</div>

</body>
</html>

Here is the CSS code.

.carousel-container {
  position: relative;
  max-width: 800px;
  margin: 0 auto;
}

.carousel-wrapper {
  overflow: hidden;
}

.carousel {
  display: flex;
  transition: transform 0.5s ease;
}

.carousel img {
  width: 200px; /* Set your desired width */
  height: auto;
  margin-right: 20px; /* Add spacing between images */
}

.prev, .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  cursor: pointer;
  padding: 10px;
  font-size: 18px;
}

.prev {
  left: 0;
}

.next {
  right: 0;
}

And Here is the JS code.

let currentIndex = 0;
const carousel = document.querySelector('.carousel');
const slides = document.querySelectorAll('.carousel img');
const totalSlides = slides.length;
const slideWidth = slides[0].clientWidth;

// Preload images
for (let i = 0; i < totalSlides; i++) {
  const img = new Image();
  img.src = slides[i].src;
}

function moveSlide(direction) {
  currentIndex = (currentIndex + direction + totalSlides) % totalSlides;
  const newPosition = -currentIndex * slideWidth;
  carousel.style.transition = 'transform 0.5s ease';
  carousel.style.transform = `translateX(${newPosition}px)`;

  // Preload next image
  const nextIndex = (currentIndex + 1) % totalSlides;
  const nextImage = new Image();
  nextImage.src = slides[nextIndex].src;
}

You can check the demo link here.

Demo

Exit mobile version