If you’re looking for a touch-friendly draggable image slider or carousel slider that is created with vanilla JavaScript without using any external library or plugin then, this blog is written for you. But for a Swiperjs Image Slider, you can view this blog on Image Slider in HTML CSS and Swiperjs.
In this blog, you’ll learn how to Create A Draggable Image Slider in HTML CSS & JavaScript from scratch. This slider supports all major browsers like Chrome, Firefox, and Edge as well as works on mobile or tab devices because of its responsiveness and touch-friendly feature.
If you don’t know, an image slider or carousel is a useful and crucial UI component of the website that is used to showcase multiple images, videos, or graphics in a single horizontal space.
In my draggable image slider, there are some images where users can slide them by dragging or using the next and previous icons. On the desktop screen, there are three images at a time but on the mobile screen, there will be one image at a time.
If you’re excited to view a live demo of this Draggable Image Slider, you can click here to view it and for a full video tutorial of this slider, you can watch the given YouTube video.
Video Tutorial of Draggable Image Slider in JavaScript
I hope you liked the demo of the Draggable Image Slider and understood the codes and logic behind creating this slider. In the video, you’ve seen I didn’t use any external plugins like Swiperjs or Owl carousel to create this touch-friendly image carousel. It’s all done with pure JavaScript.
If you haven’t watched the video, you can continue reading the blog and follow the given steps to create this Draggable Image Slider by yourself. Otherwise, go to the bottom of this blog post to download the source code files of it.
You may like this:
- Easy Image Editor in JavaScript
- Custom Video Player in JavaScript
- Random Password Generator JavaScript
- Image Compress & Resize in JavaScript
Draggable Image Slider in JavaScript [Source Codes]
To create a Draggable Image Slider using HTML CSS & JavaScript, follow the given steps line by line:
- Create a folder. You can put any name of this folder and create the below-mentioned files inside this folder.
- Create an index.html file. The file name must be index and its extension .html
- Create a style.css file. The file name must be style and its extension .css
- Create a script.js file. The file name must be script and its extension .js
- Download the images folder from Google Drive and put this folder inside the project folder.
First, paste the following codes into your index.html file.
<!DOCTYPE html> <!-- Coding By CodingNepal - youtube.com/codingnepal --> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Draggable Image Slider | CodingNepal</title> <link rel="stylesheet" href="style.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"> <script src="script.js" defer></script> </head> <body> <div class="wrapper"> <i id="left" class="fa-solid fa-angle-left"></i> <div class="carousel"> <img src="images/img-1.jpg" alt="img" draggable="false"> <img src="images/img-2.jpg" alt="img" draggable="false"> <img src="images/img-3.jpg" alt="img" draggable="false"> <img src="images/img-4.jpg" alt="img" draggable="false"> <img src="images/img-5.jpg" alt="img" draggable="false"> <img src="images/img-6.jpg" alt="img" draggable="false"> <img src="images/img-7.jpg" alt="img" draggable="false"> <img src="images/img-8.jpg" alt="img" draggable="false"> <img src="images/img-9.jpg" alt="img" draggable="false"> </div> <i id="right" class="fa-solid fa-angle-right"></i> </div> </body> </html>
Second, paste the following codes into your style.css file.
/* Import Google font - Poppins */ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ display: flex; padding: 0 35px; min-height: 100vh; align-items: center; justify-content: center; background: #343F4F; } .wrapper{ display: flex; max-width: 1200px; position: relative; } .wrapper i{ top: 50%; height: 44px; width: 44px; color: #343F4F; cursor: pointer; font-size: 1.15rem; position: absolute; text-align: center; line-height: 44px; background: #fff; border-radius: 50%; transform: translateY(-50%); transition: transform 0.1s linear; } .wrapper i:active{ transform: translateY(-50%) scale(0.9); } .wrapper i:hover{ background: #f2f2f2; } .wrapper i:first-child{ left: -22px; display: none; } .wrapper i:last-child{ right: -22px; } .wrapper .carousel{ font-size: 0px; cursor: pointer; overflow: hidden; white-space: nowrap; scroll-behavior: smooth; } .carousel.dragging{ cursor: grab; scroll-behavior: auto; } .carousel.dragging img{ pointer-events: none; } .carousel img{ height: 340px; object-fit: cover; user-select: none; margin-left: 14px; width: calc(100% / 3); } .carousel img:first-child{ margin-left: 0px; } @media screen and (max-width: 900px) { .carousel img{ width: calc(100% / 2); } } @media screen and (max-width: 550px) { .carousel img{ width: 100%; } }
Last, paste the following codes into your script.js file.
// Select elements const carousel = document.querySelector(".carousel"); const firstImage = carousel.querySelector("img"); const arrowIcons = document.querySelectorAll(".wrapper i"); // Variables for state management let isDragging = false; let startX = 0; let scrollStart = 0; let scrollDiff = 0; // Helper function to toggle arrow visibility const toggleArrowIcons = () => { setTimeout(() => { const maxScroll = Math.round(carousel.scrollWidth - carousel.clientWidth); arrowIcons[0].style.display = carousel.scrollLeft <= 0 ? "none" : "block"; arrowIcons[1].style.display = Math.round(carousel.scrollLeft) >= maxScroll ? "none" : "block"; }, 100); }; // Helper function to smoothly scroll the carousel const scrollCarousel = (direction) => { const cardWidth = firstImage.clientWidth + 14; // Image width + margin const maxScroll = carousel.scrollWidth - carousel.clientWidth; const scrollAmount = direction === "right" ? cardWidth : -cardWidth; carousel.scrollLeft = Math.min(Math.max(carousel.scrollLeft + scrollAmount, 0), maxScroll); toggleArrowIcons(); }; // Event listeners for arrows arrowIcons.forEach((icon) => { icon.addEventListener("click", () => { const direction = icon.id === "right" ? "right" : "left"; scrollCarousel(direction); }); }); // Automatic adjustment after dragging const autoCenterImage = () => { const cardWidth = firstImage.clientWidth + 14; const offset = carousel.scrollLeft % cardWidth; const maxScroll = carousel.scrollWidth - carousel.clientWidth; if (carousel.scrollLeft > 0 && carousel.scrollLeft < maxScroll) { if (offset > cardWidth / 3) { carousel.scrollLeft += cardWidth - offset; // Snap to the next image } else { carousel.scrollLeft -= offset; // Snap to the previous image } } toggleArrowIcons(); }; // Dragging logic const startDragging = (event) => { isDragging = true; startX = event.pageX || event.touches[0].pageX; scrollStart = carousel.scrollLeft; carousel.classList.add("dragging"); }; const duringDrag = (event) => { if (!isDragging) return; const currentX = event.pageX || event.touches[0].pageX; scrollDiff = currentX - startX; carousel.scrollLeft = scrollStart - scrollDiff; }; const stopDragging = () => { if (!isDragging) return; isDragging = false; carousel.classList.remove("dragging"); if (Math.abs(scrollDiff) > 10) { autoCenterImage(); } }; // Attach event listeners carousel.addEventListener("mousedown", startDragging); carousel.addEventListener("touchstart", startDragging); document.addEventListener("mousemove", duringDrag); carousel.addEventListener("touchmove", duringDrag); document.addEventListener("mouseup", stopDragging); carousel.addEventListener("touchend", stopDragging); // Initial setup toggleArrowIcons();
That’s all, now you’ve successfully created a Draggable Image Slider in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced problems, please download the source code files using the download button. It’s free and a zip file containing the project folder with source code files and images will be downloaded.
Brother, I want to use the slider on the same page more than once, but when I put that, only the first slider works