Get the touch coordinate for the current item

So, I have an element that looks like this:

____________________________________ / \ | | | | +------------------------------------+ | | | | | | +------------------------------------+ | | | | \____________________________________/ 

I connected a touchstart listener to it, for example:

  other_options.addEventListener('touchstart', function(e) { event.preventDefault(); }, false); 

What I want to do, and I have already looked at the values โ€‹โ€‹of "e", but I can not find any value that is consistent enough (the values โ€‹โ€‹seem to me wrong when I try to) to do what I want.

I know the size of these lines. I just want to be able to take the Y coordinate where the touchstart event occurred, 0 is the top coordinate of the element. So Math.floor (y / ROW_SIZE) will give me the line where the touchstart event was fired.

+8
javascript html html5
source share
2 answers

You need to access this way.

 e.touches[0].clientX/clientY. 

number of touches and touch information can be accessed through e.touches.

Take a look at this FAQ.

How to get x / y coordinates in touch events?

here is the touch documentation event.

By the way, events will return x / y coordinates relative to only the window. we cannot change that. what you can do it. top= 0 - element.top; x= clientx-top.

+10
source share

It is better to use the getBoundingClientRect() method to calculate the top and left values โ€‹โ€‹of an element.

The element.top approach element.top may not indicate the top and left values โ€‹โ€‹relative to the viewport if the element is inside another container.

So, to calculate the coordinates of the touch relative to the element, we can do as shown below.

 var rect = element.getBoundingClientRect(); xCoordinate = event.touches[0].clientX - rect.left; yCoordinate = event.touches[0].clientY - rect.top; 

To learn more about the getBoundingClientRect() method, click here .

+1
source share

All Articles