1

On implementing drag-n-drop of an image for touch devices, I have a problem converting touch events to mouse events. Events are not dispatched or don't work as supposed. I used this guide and learnt other answers.

To minimize the question, I'll narrow to the drag event only, without drop. Hopefully if it's solved, the other part will be solved, too. When I drag the image with mouse, I get the desired behavior - the ghostly image and the changed cursor:

enter image description here

I need to have the same ghostly image when touch-drag on a device, but no luck:

enter image description here

In order to achieve the desired behavior, I try to simulate a mouse event when touch event happens.

<img id="hammer" src="https://i.stack.imgur.com/9oV2e.png" />

<script>
var hammer = document.getElementById("hammer");

hammer.addEventListener("touchstart", touchHandler, true);
hammer.addEventListener("touchmove", touchHandler, true);

function touchHandler(event) {
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
    switch(event.type) {
        case "touchstart": type = "dragstart"; break;
        case "touchmove":  type = "drag";      break;        
        default:           return;
    }

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                                  first.screenX, first.screenY, 
                                  first.clientX, first.clientY, false, 
                                  false, false, false, 0/*left*/, first.target);
    
    this.dispatchEvent(simulatedEvent);
    event.preventDefault();
}
</script>

The fiddle

It seems that the touch events are not converted to drag events. How can I achieve it? If I add EventListeners to document instead of hammer, I get an error. If I wrap hammer with a container div, and addEventListener to the container, it gives no success, too. If I change type = "drag" to type = "mousemove", no difference.

HoRn
  • 1,458
  • 5
  • 20
  • 25

0 Answers0