I am trying to get jQuery drag/drop to work nicely with iPad touch events. I found this code on the internet:
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch (event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type = "mousemove"; break;
case "touchend": type = "mouseup"; break;
default: return;
}
//initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
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*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
It appears to work fine if I attach the touchHandler to the document
touchstart/move/end, but then no native zooming/scrolling on the iPad is allowed, so I am trying to just attach this handler to the draggables themselves.
The issue that I am seeing with this is that event.changeTouches
is always undefined for some reason, as you can witness in http://jsfiddle.net/myLj2/1/ . I can't come up with a reason why a touch event will always have an undefined changeTouches
property and because of it, this code won't work. Any thoughts?
changedTouches property is a TouchList object that contains one Touch object for each touch point which contributed to the event. In following code snippet, the touchmove event handler iterates through the changedTouches list and prints the identifier of each touch point that changed since the last event.
When a visitor clicks on an image the click event will be triggered. However when someone touches the image, that same click event will be triggered, even if a touchstart event is available as well.
I figured it out after discovering Does jQuery preserve touch events properties?.
It turns out that the jQuery event doesn't copy over the changeTouches
property, so you have to either use jQuery's originalEvent
property or skip jQuery all together and bind with a function like addEventListener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With