Touch Image Slider using HTML & JavaScript

In this tutorial I will tell you how to create Touch Image Slider using HTML, CSS and JavaScript. Image sliders can be easily created with HTML and CSS, but the content has to be controlled with text.

With this Touch Image Slider you can change the image by touch. The image can be changed by dragging on non-touch devices.

I have taken the help of HTML, CSS and JavaScript to create this Touch and Drag Image Slider.

Touch Image Slider with HTML CSS JavaScript

Image sliders are a popular way to showcase multiple images or content in a visually appealing manner on websites.

A Touch Image Slider, also known as a touch image carousel or slider, is a user interface element commonly used on websites and mobile applications to showcase a series of images or content in a visually appealing way. 

Adding touch functionality to these sliders enhances the user experience on mobile devices. In this article, we will guide you through the process of creating a touch-enabled image slider using HTML and JavaScript.

See the Pen Untitled by Growthpanda (@Growthpanda) on CodePen.

As you have seen this Touch Slider can be controlled by dragging in case of laptop and desktop and touch in case of mobile. Here I have used 5 images. You can change its structure as you like. So let’s know how Touch Image Slider is made.

Step 1: Structure of Touch Image Slider

Let’s start by setting up the HTML structure for our image slider. Here I have created a structure for the image slider. I will add the images by javascript.

<div class="container">
   <div class="slider-inner"></div>
</div>

Step 2: CSS Code of Touch Slider

Now, let’s add some basic styling to our slider. Create a new file called styles.css.  I have used the following CSS to design the Touch Image Slider HTML.

* {
  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;
}

Step 3: Activate the Touch Image Slider

Now, let’s add the JavaScript functionality to enable touch-based sliding. Create a new file called script.js I used a lot of JavaScript to activate the Touch Image Slider. But I have explained all the code fully though. Hope you don’t have trouble understanding. . 

1. Initial References:
const sliderContainer = document.querySelector(".container");
const innerSlider = document.querySelector(".slider-inner");
let innerContainer = innerSlider.getBoundingClientRect();
let outerContainer = sliderContainer.getBoundingClientRect();
  • The code starts by selecting the container and inner slider elements using document.querySelector().

  • It then retrieves the initial bounding rectangles of the inner slider and the container.

2. Slider Variables:
let active = false,
  startX = 0;

const images = [
  // Array of image URLs
];

let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";
  • Variables like active and startX are initialized to manage the slider state.

  • An array images stores URLs of the images to be displayed in the Touch Image Slider.

  • The events object stores mouse and touch events based on the device type.

  • The deviceType variable is set based on whether the device supports touch events.

3. 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)`;
};
  • The slideGenerator function dynamically generates HTML for each image and appends it to the inner slider.

  • Each image is wrapped in a div with the class “slide,” and an img element is added with the image URL.

  • The gridTemplateColumns style is set to create a grid layout with columns for each image.

4. isTouchDevice Function:
const isTouchDevice = () => {
  try {
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};
  • The isTouchDevice function checks if the device supports touch events.

  • It tries to create a TouchEvent and sets deviceType accordingly.

5. Mouse/Touch Event Listeners:
sliderContainer.addEventListener(events[deviceType].down, (e) => {
  active = true;
  startX =
    (!isTouchDevice()
      ? e.clientX
      : e.touches[0].clientX - outerContainer.left) - innerSlider.offsetLeft;
  sliderContainer.style.cursor = "grabbing";
});

sliderContainer.addEventListener(events[deviceType].up, () => {
  sliderContainer.style.cursor = "grab";
  active = false;
});

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();
  }
});
  • Event listeners are added for mouse/touch down, move, and up events on the sliderContainer.

  • On mouse/touch down, the active state is set, and the initial position (startX) is calculated based on the event type and coordinates.

  • On mouse/touch up, the cursor style is updated, and the active state is reset.

  • On mouse/touch move, if the slider is active, it updates the position based on the difference between the current and start positions.

6. Check Boundary Function:
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`;
  }
};
  • The checkBoundary function ensures that the slider does not move beyond its boundaries.

  • If the Touch Image Slider is dragged beyond the left edge, it sets the position to 0.

  • If the slider is dragged beyond the right edge, it sets the position to keep the last image visible.

7. Window Load Event:
window.onload = () => {
  slideGenerator();
};

The window.onload event triggers the slideGenerator function when the page is fully loaded, generating and displaying the slides.

By following these steps, you’ve successfully created a touch image slider using HTML, CSS, and JavaScript. This slider enhances the user experience on both desktop and mobile devices, allowing users to navigate through images seamlessly with touch gestures.

Let me know how you like this tutorial by commenting.

Leave a Comment

Home
Menu
Instagram
Search