8

As Mozilla states on the TouchEvent page:

The event's target is the same element that received the touchstart event corresponding to the touch point, even if the touch point has moved outside that element.

This is not the same as mousemove and mouseup, where the target really is the DOM element that the mouse is over.

What's the best way, without using any library, to get the element that my touchmove or touchend event occurs on?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simon Sarris
  • 62,212
  • 13
  • 141
  • 171

1 Answers1

7

Read the coordinates (pageX and pageY) from the event object. Then use document.elementFromPoint(x, y) to get the top element at that position.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    `pageX` and `pageY` are properties of a [`Touch`](https://developer.mozilla.org/en/DOM/Touch) object, which is an element in a `TouchList`, which is the [`TouchEvent.touches`](https://developer.mozilla.org/en/DOM/TouchEvent.touches) property. – Rob W May 08 '12 at 21:11
  • 2
    ... which does not exist in some browsers (i.e.: chrome for Android). – Mister Smith Jul 15 '13 at 09:48
  • Maybe you mean [`clientX` and `clientY` rather than `pageX` and `pageY`](https://stackoverflow.com/a/74946571/5231110), respectively. See also [this implementation](https://stackoverflow.com/a/39053913/5231110). – root Apr 02 '23 at 08:47