HomeJavascriptTouch and Drag Image Slider

Touch and Drag Image Slider

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.

Previous articleMCQ – 2/2/23
Next articleMCQ – 4/2/23
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5 − three =

Most Popular