JavaScript for Touch and Dragging Horizontally for Mobile


Implement touch and dragging horizontally on mobile devices

To implement touch and dragging horizontally on mobile devices using JavaScript, you can use the touchstart, touchmove, and touchend events. Here's a basic example:

"<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Touch and Drag Example</title>
#draggable {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

<div id="draggable"></div>

var draggable = document.getElementById('draggable');
var offsetX, offsetY;

// Touch start event
draggable.addEventListener('touchstart', function(e) {
var touch = e.touches[0];
offsetX = touch.clientX - draggable.getBoundingClientRect().left;
offsetY = touch.clientY - draggable.getBoundingClientRect().top;

// Touch move event
draggable.addEventListener('touchmove', function(e) {
e.preventDefault(); // Prevent scrolling
var touch = e.touches[0];
var x = touch.clientX - offsetX;
var y = touch.clientY - offsetY; = x + 'px'; = y + 'px';

// Touch end event
draggable.addEventListener('touchend', function(e) {
// Any additional logic when touch ends


This code creates a blue square that can be dragged horizontally on touch devices. Here's a breakdown:

  1. The touchstart event retrieves the initial touch position when the user touches the element.
  2. The touchmove event updates the element's position as the user drags their finger across the screen. It calculates the new position based on the difference between the current touch position and the initial touch position.
  3. The touchend event can be used for any additional logic when the touch interaction ends, if needed.

Leave a comment

Your email address will not be published. Required fields are marked *

Please note, comments must be approved before they are published

Related aticles