Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind dragstart and drop events to touch events

Referring to this answer: https://stackoverflow.com/a/6362527/3034646

How would I bind the touch events such that they will perform the dragstart and drop events? I've tried binding dragstart to touchdown and drop to touchup but this results in dragstart not picking up on dataTransfer.get/setData.

Is it possible to map the touch events to replicate dragstart and drop?

like image 703
Jimmy T Avatar asked Sep 05 '25 03:09

Jimmy T


1 Answers

1.Touchstart Event: This event will serve as the equivalent of dragstart. It triggers when the user touches the screen.

  1. Touchmove Event: This event will simulate dragging behavior. It triggers when the user moves their finger while touching the screen.
  2. Touchend Event: This event will serve as the equivalent of drop. It triggers when the user lifts their finger off the screen after dragging.

// Get the element you want to make draggable
var draggableElement = document.getElementById('draggable');

// Add event listeners for touch events
draggableElement.addEventListener('touchstart', handleTouchStart, false);
draggableElement.addEventListener('touchmove', handleTouchMove, false);
draggableElement.addEventListener('touchend', handleTouchEnd, false);

// Variable to store initial touch position
var initialX = null;
var initialY = null;

// Function to handle touchstart event
function handleTouchStart(event) {
    // Store initial touch position
    initialX = event.touches[0].clientX;
    initialY = event.touches[0].clientY;
}

// Function to handle touchmove event
function handleTouchMove(event) {
    if (!initialX || !initialY) {
        return;
    }

    // Calculate the distance moved
    var deltaX = event.touches[0].clientX - initialX;
    var deltaY = event.touches[0].clientY - initialY;

    // Update the element's position
    draggableElement.style.transform = 'translate(' + deltaX + 'px, ' + deltaY + 'px)';
    
    // Prevent scrolling
    event.preventDefault();
}

// Function to handle touchend event
function handleTouchEnd(event) {
    // Reset initial touch position
    initialX = null;
    initialY = null;

    // Perform actions equivalent to drop event
    // For example, you can save the final position or perform any other necessary action
}
like image 98
Mahendran ThanuJjan Avatar answered Sep 07 '25 21:09

Mahendran ThanuJjan