Draggable Image Slider using Pure JavaScript and CSS Tutorial

In this tutorial, you will learn how to Create a Draggable Image Slider using CSS and Pure JavaScript. The tutorial aims to provide IT/CS students and new programmers with a reference for learning and gaining some more knowledge of using CSS and JavaScript for developing a web application with a creative user interface and functionalities. Here, snippets will be provided to give you more ideas for achieving the goal of this tutorial. A sample source code zip file is also provided and is free to download.

What is Draggable Image Slider?

The Draggable Image Slider is actually an Image Slider with drag functionality which is one of the useful UI components of a website or a web application. It displays multiple images that are related to the site or anything. Implementing a drag functionality in an image slider allows the user to navigate images from the current to the previous or next image or slide item. Image Sliders commonly come with dragging and next/previous navigation buttons.

How to Create a Draggable Image Slider using CSS and JavaScript?

Using CSS scripts, we can design our Image Slider according to our requirements or desire while JavaScript will the responsible for achieving the dragging functionality of the said component.

Here are the steps for creating a simple Draggable Image Slider

Step 1: Create the Image Slider Interface

First, we will need to create an HTML script for the Image Slider that they wanted. The HTML script contains the elements of the Image Slider including the images to display on the said component. Below is an example HTML script of an Image Slider.

  1. <div id="slider-container">
  2. <div id="slider-flex">
  3. <div class="slider-item">
  4. <img src="./assets/images/img-1.jpg" alt="Image 1">
  5. </div>
  6. <div class="slider-item">
  7. <img src="./assets/images/img-2.jpg" alt="Image 2">
  8. </div>
  9. <div class="slider-item">
  10. <img src="./assets/images/img-3.jpg" alt="Image 3">
  11. </div>
  12. <div class="slider-item">
  13. <img src="./assets/images/img-4.jpg" alt="Image 4">
  14. </div>
  15. <div class="slider-item">
  16. <img src="./assets/images/img-5.jpg" alt="Image 5">
  17. </div>
  18. </div>
  19. </div>

In the above HTML script, the #slider-container is the main element of the Image slider. The .slider-flex is the sub-container of the component which will be used for making the image display horizontally. The .slider-item is the element that holds the images.

Step 2: Creating the CSS Script

Next, we will create the Cascading Stylesheet (CSS) script of the Image Slider Component. Using the CSS, we can achieve the desired interface design of our Image Slider Component. See the following sample snippet below.

 

  1. #slider-container {
  2. position: relative;
  3. overflow: hidden;
  4. width: 100%;
  5. }
  6. #slider-flex {
  7. position: relative;
  8. display: flex;
  9. width: calc(100% * 5);
  10. height: 60vh;
  11. }
  12. .slider-item {
  13. width: calc(100%);
  14. position: relative;
  15. height: 60vh;
  16. top: 0;
  17. cursor: pointer;
  18. }
  19.  
  20. .slider-item>img {
  21. width: 100%;
  22. height: 100%;
  23. object-fit: cover;
  24. object-position: bottom center;
  25. }

Using the provided CSS Script, the Image Slider will be displayed with a simple container that displays only 1 of the items added to the component. If you use the inspect elements of your browser, you will find that the other images are only hidden beside the visible one.

Step3: Creating the JavaScript

Lastly, we will need to create some script using JavaScript to create a Draggable Functionality of our Image Slider. Using the built-in API and methods of JavaScript such as the mouse move event listener, we can achieve the dragging functionality. See the sample snippet below (comments are included on the snippet to have a better idea).

 

  1. /** Draggable Slider */
  2. const slider = document.getElementById('slider-container')
  3. const sliderFlex = document.getElementById('slider-flex')
  4. const slideritems = document.querySelectorAll('#slider-flex .slider-item')
  5.  
  6. // Variable of X-axis position where Mouse move started
  7. var Xposition = 0;
  8. // Variable of X-axis position when Mouse is moving
  9. var XpositionMove = 0;
  10. // Variable of X-axis position of for slide animation/transition when mousemove
  11. var XNewPosition = 0;
  12. // Variable of X-axis position difference from start to end of mousemove
  13. var slide = 0;
  14. // Variable of X-axis Final position of sliding animation/transition when mousemove end (Updates when mouseup)
  15. var XNewPositionFinal = 0;
  16. // Variable of X-axis current position (Updates when mouseup)
  17. var currentPosition = 0;
  18. // width of the Slider Image
  19. var itemWidth = slideritems[0].clientWidth;
  20. // maximum width for animating the slider items
  21. var maxslide = itemWidth * (slideritems.length - 1);
  22.  
  23. /**
  24.   * Start of Slider/Image Dragging Function
  25.   */
  26. function startDragging(e){
  27. e.preventDefault()
  28. Xposition = e.clientX;
  29.  
  30. //start slider animation/transition onmousemove
  31. document.addEventListener('mousemove', startMove)
  32. //End of mouse move
  33. document.addEventListener('mouseup', function(e){
  34. document.removeEventListener('mousemove',startMove)
  35. XNewPositionFinal = XNewPositionFinal + XNewPosition
  36. if(slide < 0){
  37. /** Slide Next */
  38. if(Math.abs(slide) > 150 && Math.abs(currentPosition - itemWidth) <= maxslide){
  39. currentPosition = currentPosition - itemWidth
  40. }
  41. }else{
  42. /** Slide Privous */
  43. if(Math.abs(slide) > 150 && Math.abs(currentPosition - itemWidth) > itemWidth){
  44. currentPosition = currentPosition + itemWidth
  45. }
  46. }
  47. slideritems.forEach(el => {
  48. // Add transition to element temporarily
  49. el.style.transition = `left .5s ease-in-out`;
  50. el.style.left = `${currentPosition}px`
  51.  
  52. // Remove transition to element
  53. setTimeout(()=>{
  54. el.style.transition = `none`;
  55. }, 800)
  56.  
  57. })
  58.  
  59. /** Reset Variables */
  60. XNewPositionFinal = currentPosition
  61. Xposition = 0;
  62. XpositionMove = 0;
  63. XNewPosition = 0;
  64. slide = 0;
  65. })
  66. }
  67. /**
  68.   * Animate Slider onmousemove Function
  69.   */
  70. function startMove(e){
  71. e.preventDefault()
  72. XpositionMove = e.clientX;
  73. slide = XpositionMove - Xposition
  74. XNewPosition = XNewPositionFinal + slide
  75.  
  76. /** Move Slide Items */
  77. slideritems.forEach(el => {
  78. el.style.left = `${XNewPosition}px`
  79. })
  80. }
  81.  
  82. // Start Drag
  83. slideritems.forEach(slideItem => {
  84. slideItem.addEventListener('mousedown', startDragging)
  85. })

The script above allows the user the drag or swipe the images on the slider component. It will also allow them to navigate to the next or previous image item. Take note, the script below does not come with infinite sliding of images.

Sample Source Code

I have also provided a sample application source code zip file that I created that demonstrates the usage of given snippets for achieving the Draggable Image Slider. You can download it by clicking the download button below this article.

Snapshot

Here is the snapshot of the interface of the sample application that I provided.

Draggable Image Slider using JS

That's the end of this tutorial! Feel free to download and modify the source code file that I provided the way you wanted. I hope this Draggable Image Slider will help you with what you are looking for and that you'll find this useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment