Get mousemove and touchmove element target
Hello everybody,
You may have noticed while monitoring a touchmove event that the e.target
value represents the element where the touch event began.
While on mousemove the target is always the element under the mouse cursor, on touch it seems to behave differently.
In order to retrieve that element, we can only identify it from the touch event coordinates as it follows:
getTouchMouseTargetElement(e) {
if (e.touches) {
return document.elementFromPoint(e.touches[0].pageX, e.touches[0].pageY);
}
return e.target;
}
e.touches
is a TouchList. It lists all the Touch objects for touch points that are currently in contact with the touch surface, regardless of whether or not they’ve changed or what their target element was at touchstart time.
If the event has no TouchList defined, the e.target
can be taken as a fallback (in case of mouse events).
This way we implemented a single function that works with both mouse and touch events.
No comments yet.