How to get touchEnd to behave just like mouseUp?
This was a fun question to tackle. Thanks for that.
Here's what I have done. I have modified your touchmove
handler as such:
function onDocumentTouchMove(event) {
onDocumentTouchMove.x = event.changedTouches[event.changedTouches.length - 1].clientX;
onDocumentTouchMove.y = event.changedTouches[event.changedTouches.length - 1].clientY;
}
In this handler I'm saving the last co-ordinate that the user moved to. In all probability, this is the point at which the user took his finger, nose, knuckle, stylus, etc off the touch surface. These co-ordinates I then use in the handler for touchend
to find the element that surrounds them.
function onDocumentTouchEnd(event) {
event.preventDefault();
var elem = document.elementFromPoint(onDocumentTouchMove.x, onDocumentTouchMove.y);
elem.style.background = "#ff0000";
}
I have utilized the document.elementFromPoint
(mdn link) for this purpose. It is one of those golden yet fairly unknown methods provided to us by the CSSOM spec.
Here's the fiddle.