Find an Element’s Position Using Javascript

I went through quite a few Google searches trying to figure this out. My problem was that I needed to get the coordinate of a touch event relative to the top left corner of an element. However, the TouchEvent object doesn’t have theĀ offsetX or offsetY, which, in contrast, the MouseEvent object does have and allows you to get exactly what you want, the X/Y coordinate of the event (in the case of MouseEvent, the mouseup, mousedown, or click). Unfortunately, you’ll have to figure out a different way to do this with TouchEvent.

My idea was simple (at least that’s what I thought initially): the TouchEvent object provides the X/Y coordinates of where the touch event occurred, so I’ll just grab the target element’s position and subtract out the top and left position. From my initial searches, figuring out an element’s position wasn’t straightforward. At all. I read a few articles that talked about adding up all the offset positions from the element outward (i.e. every single parent’s offset position). Yeesh. Then I remembered a project I worked on that required me to pop up a “speech bubble” on the element that the user tapped on.

Solution: getBoundingClientRect

What the getBoundingClientRect function returns is a ClientRect object, which will provide an element’s top corner position relative to the viewport. The targetTouches object will provide information on where the user tapped on relative to the viewport (i.e. the clientX and clientY properties). You’ll need to do a little calculation, but to get the coordinate of the touch event within the element is fairly straight forward:

var x = event.targetTouches[0].clientX - event.target.getBoundingClientRect().left
var y = event.targetTouches[0].clientY - event.target.getBoundingClientRect().top

If you’re worried about compatibility, apparently IE supported this since version 5 (wow). Have fun coding.