Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn JavaScript. So in todayโs tutorial let us expand our JavaScript knowledge with a fun and easy-to-build project called โTouch and Drag Image Sliderโ. To build this project we need HTML, CSS, and JavaScript.
Video Tutorial:
Before we move on to the actual tutorial, you can check out the video tutorial of this post here. If you like video tutorials like this subscribe to my YouTube channel, where I post new projects based on HTML, CSS, and JavaScript regularly.
Project Folder Structure:
Letโs build the project folder structure before we begin writing the code. We create a project folder called โDrag To Scroll Imagesโ. Inside this folder, we have three files. These files are โindex.htmlโ, โstyle.cssโ, and โscript.jsโ.
HTML:
Letโs build the project folder structure before we begin writing the code. We create a project folder called โDrag To Scroll Imagesโ. Inside this folder, we have three files. These files are โindex.htmlโ, โstyle.cssโ, and โscript.jsโ.
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Draggable Image Slider</title> <!-- Stylesheet --> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="container"> <div class="slider-inner"></div> </div> <!-- Script --> <script src="script.js"></script> </body> </html>
CSS:
Letโs build the project folder structure before we begin writing the code. We create a project folder called โDrag To Scroll Imagesโ. Inside this folder, we have three files. These files are โindex.htmlโ, โstyle.cssโ, and โscript.jsโ.
* { box-sizing: border-box; } body { margin: 0; padding: 0; background-color: #000000; } img { width: 100%; } .hide { display: none; } .container { position: absolute; left: 5%; top: 10%; width: 90%; height: 80vh; overflow: hidden; cursor: grab; } .slider-inner { position: absolute; top: 2%; left: 0px; width: 500%; height: 100%; display: grid; gap: 1rem; pointer-events: none; }
Javascript:
Finally, we add functionality to the slider using Javascript. For this once again copy the code below and paste it into your script file. You can add as many images as you like inside your folder and store the file name in the โimagesโ array to make the slider more attractive.
The steps included in creating this slider are:
- Create Initial References to HTML elements.
- Create โslideGenerator()โ, which is used to append the images into the โinnerSliderโ div.
- Then create โisTouchDevice()โ, which gives us the device type so that we could use it for responsible behavior. This also helps us to decide on the event to use based on device type.
- When the user clicks we set โactive=trueโ to imply that the user has started dragging the image and we store the x-coordinate in the โstartXโ variable.
- When the user moves the cursor firstly we check if โactiveโ is โtrueโ then we set โcurrentXโ to the current x-coordinate after which we set the left alignment for โinnerSliderโ to the difference between โcurrentXโ and โstartXโ.
- Finally, we will create a โcheckBoundary()โ function to make sure that the first and last slides cannot be a drag.
//Initial References const sliderContainer = document.querySelector(".container"); const innerSlider = document.querySelector(".slider-inner"); let innerContainer = innerSlider.getBoundingClientRect(); let outerContainer = sliderContainer.getBoundingClientRect(); //Slider variables let active = false, startX = 0; const images = [ "slider-img-1.jpeg", "slider-img-2.jpeg", "slider-img-3.jpeg", "slider-img-4.jpeg", "slider-img-5.jpeg", "slider-img-6.jpg", "slider-img-7.jpg", ]; let events = { mouse: { down: "mousedown", move: "mousemove", up: "mouseup", }, touch: { down: "touchstart", move: "touchmove", up: "touchend", }, }; let deviceType = ""; const isTouchDevice = () => { try { document.createEvent("TouchEvent"); deviceType = "touch"; return true; } catch (e) { deviceType = "mouse"; return false; } }; //Generates Slides const slideGenerator = () => { for (let i of images) { const div = document.createElement("div"); div.classList.add("slide"); div.innerHTML = `<img src='${i}' class='image'>`; innerSlider.appendChild(div); } innerSlider.style.gridTemplateColumns = `repeat(${images.length},1fr)`; }; isTouchDevice(); //Mousedown sliderContainer.addEventListener(events[deviceType].down, (e) => { active = true; startX = (!isTouchDevice() ? e.clientX : e.touches[0].clientX - outerContainer.left) - innerSlider.offsetLeft; sliderContainer.style.cursor = "grabbing"; }); //Mouseup sliderContainer.addEventListener(events[deviceType].up, () => { sliderContainer.style.cursor = "grab"; active = false; }); //MouseMove sliderContainer.addEventListener(events[deviceType].move, (e) => { if (active) { e.preventDefault(); let currentX = !isTouchDevice() ? e.clientX : e.touches[0].clientX - outerContainer.left; innerSlider.style.left = `${currentX - startX}px`; checkBoundary(); } }); const checkBoundary = () => { innerContainer = innerSlider.getBoundingClientRect(); outerContainer = sliderContainer.getBoundingClientRect(); if (parseInt(innerSlider.style.left) >= 0) { innerSlider.style.left = "0px"; } else if (innerContainer.right < outerContainer.right) { innerSlider.style.left = `-${ innerContainer.width - outerContainer.width }px`; } }; window.onload = () => { slideGenerator(); };
Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the โDownload Codeโ button below.