Crafting an Amazing Image Slider with JavaScript

image slider

In this tutorial, we’ll explore how to create a stylish and customizable image slider using HTML, CSS, and JavaScript. This image slider is equipped with intuitive navigation buttons and a scrollbar for smooth user interaction.

HTML Structure:

The HTML structure comprises a container div housing the slider components. Within the container, we have a slider-container div containing navigation buttons, an image grid, and a scrollbar.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Image Slider | Custom Design</title>
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@48,400,0,0"
    />
  </head>
  <body>
    <div class="container">
      <div class="slider-container">
        <button id="previous-slide" class="slide-button material-symbols-rounded">
          chevron_left
        </button>
        <ul class="image-grid">
          <img class="image-item" src="images/img-1.jpg" alt="img-1" />
          <img class="image-item" src="images/img-2.jpg" alt="img-2" />
          <img class="image-item" src="images/img-3.jpg" alt="img-3" />
          <img class="image-item" src="images/img-4.jpg" alt="img-4" />
          <img class="image-item" src="images/img-5.jpg" alt="img-5" />
          <img class="image-item" src="images/img-6.jpg" alt="img-6" />
          <img class="image-item" src="images/img-7.jpg" alt="img-7" />
          <img class="image-item" src="images/img-8.jpg" alt="img-8" />
          <img class="image-item" src="images/img-9.jpg" alt="img-9" />
          <img class="image-item" src="images/img-10.jpg" alt="img-10" />
        </ul>
        <button id="next-slide" class="slide-button material-symbols-rounded">
          chevron_right
        </button>
      </div>
      <div class="slider-scrollbar">
        <div class="scrollbar-track">
          <div class="scrollbar-thumb"></div>
        </div>
      </div>
    </div>
  </body>
</html>
CSS

CSS Styling:

The CSS styles are meticulously crafted to achieve a visually appealing and responsive layout for the image slider. Key styling elements include:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #f1f4fd;
}

.container {
  max-width: 1200px;
  width: 95%;
}

.slider-container {
  position: relative;
}

.slider-container .slide-button {
  position: absolute;
  top: 50%;
  outline: none;
  border: none;
  height: 50px;
  width: 50px;
  z-index: 5;
  color: #fff;
  display: flex;
  cursor: pointer;
  font-size: 2.2rem;
  background: #000;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transform: translateY(-50%);
}

.slider-container .slide-button:hover {
  background: #404040;
}

.slider-container .slide-button#previous-slide {
  left: -25px;
  display: none;
}

.slider-container .slide-button#next-slide {
  right: -25px;
}

.slider-container .image-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 18px;
  font-size: 0;
  list-style: none;
  margin-bottom: 30px;
  overflow-x: auto;
  scrollbar-width: none;
}

.slider-container .image-grid::-webkit-scrollbar {
  display: none;
}

.slider-container .image-grid .image-item {
  width: 325px;
  height: 400px;
  object-fit: cover;
}

.container .slider-scrollbar {
  height: 24px;
  width: 100%;
  display: flex;
  align-items: center;
}

.slider-scrollbar .scrollbar-track {
  background: #ccc;
  width: 100%;
  height: 2px;
  display: flex;
  align-items: center;
  border-radius: 4px;
  position: relative;
}

.slider-scrollbar:hover .scrollbar-track {
  height: 4px;
}

.slider-scrollbar .scrollbar-thumb {
  position: absolute;
  background: #000;
  top: 0;
  bottom: 0;
  width: 50%;
  height: 100%;
  cursor: grab;
  border-radius: inherit;
}

.slider-scrollbar .scrollbar-thumb:active {
  cursor: grabbing;
  height: 8px;
  top: -2px;
}

.slider-scrollbar .scrollbar-thumb::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: -10px;
  bottom: -10px;
}

/* Styles for mobile and tablets */
@media only screen and (max-width: 1023px) {
  .slider-container .slide-button {
    display: none !important;
  }

  .slider-container .image-grid {
    gap: 10px;
    margin-bottom: 15px;
    scroll-snap-type: x mandatory;
  }

  .slider-container .image-grid .image-item {
    width: 280px;
    height: 380px;
  }

  .slider-scrollbar .scrollbar-thumb {
    width: 20%;
  }
}
CSS
  • Global Styles: Resetting default browser styles and defining layout properties.
  • Slider Container Styles: Styling the container for the slider components.
  • Navigation Button Styles: Customizing the appearance and position of navigation buttons.
  • Image Grid Styles: Defining the layout and appearance of the image grid.
  • Scrollbar Styles: Styling the scrollbar for smooth scrolling experience.

JavaScript Functionality:

The JavaScript code enhances the functionality of the image slider by implementing the following features:

const initializeSlider = () => {
  const imageList = document.querySelector(
    ".slider-container .image-grid"
  );
  const slideButtons = document.querySelectorAll(
    ".slider-container .slide-button"
  );
  const sliderScrollbar = document.querySelector(
    ".container .slider-scrollbar"
  );
  const scrollbarThumb =
    sliderScrollbar.querySelector(".scrollbar-thumb");
  const maxScrollLeft = imageList.scrollWidth - imageList.clientWidth;

  scrollbarThumb.addEventListener("mousedown", (e) => {
    const startX = e.clientX;
    const thumbPosition = scrollbarThumb.offsetLeft;
    const maxThumbPosition =
      sliderScrollbar.getBoundingClientRect().width -
      scrollbarThumb.offsetWidth;

    const handleMouseMove = (e) => {
      const deltaX = e.clientX - startX;
      const newThumbPosition = thumbPosition + deltaX;
      const boundedPosition = Math.max(
        0,
        Math.min(maxThumbPosition, newThumbPosition)
      );
      const scrollPosition =
        (boundedPosition / maxThumbPosition) * maxScrollLeft;

      scrollbarThumb.style.left = `${boundedPosition}px`;
      imageList.scrollLeft = scrollPosition;
    };

    const handleMouseUp = () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
  });

  slideButtons.forEach((button) => {
    button.addEventListener("click", () => {
      const direction = button.id === "previous-slide" ? -1 : 1;
      const scrollAmount = imageList.clientWidth * direction;
      imageList.scrollBy({ left: scrollAmount, behavior: "smooth" });
    });
  });

  const handleSlideButtons = () => {
    slideButtons[0].style.display =
      imageList.scrollLeft <= 0 ? "none" : "flex";
    slideButtons[1].style.display =
      imageList.scrollLeft >= maxScrollLeft ? "none" : "flex";
  };

  const updateScrollThumbPosition = () => {
    const scrollPosition = imageList.scrollLeft;
    const thumbPosition =
      (scrollPosition / maxScrollLeft) *
      (sliderScrollbar.clientWidth - scrollbarThumb.offsetWidth);
    scrollbarThumb.style.left = `${thumbPosition}px`;
  };

  imageList.addEventListener("scroll", () => {
    updateScrollThumbPosition();
    handleSlideButtons();
  });
};

window.addEventListener("resize", initializeSlider);
window.addEventListener("load", initializeSlider);
JavaScript
  • Smooth Scrolling: Enables smooth scrolling when navigating through images using the navigation buttons.
  • Scrollbar Interaction: Allows users to interact with the scrollbar to navigate through images effortlessly.
  • Dynamic Button Display: Dynamically adjusts the visibility of navigation buttons based on the current scroll position.

Responsive Design:

The image slider is designed to be responsive across various devices and screen sizes. Media queries are used to adjust the layout and dimensions of slider components for optimal viewing on mobile and tablet devices.

Conclusion:

With this tutorial, you’ve learned how to create a sleek and functional image slider from scratch using HTML, CSS, and JavaScript. You can further customize the slider’s appearance and behavior to suit your specific requirements and integrate it seamlessly into your website for showcasing images or content in an engaging manner. Experiment with different styles and features to create a unique and captivating user experience!

Happy Coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *