Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get touchstart coordinate on current element

So I have an element that looks like this:

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

I have attached a touchstart listener to it, like this:

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

What I want to do, and I've already looked through the values of 'e' but I can't find any value consistent enough (values don't seem right to me when I try them) to do what I want.

I know the size of those rows. I just want to be able to take the Y coordinate of where the touchstart event fired, being 0 the upper coordinate of the element. That way, Math.floor(y / ROW_SIZE) will give me the row the touchstart event was started on.

like image 423
h4lc0n Avatar asked Jan 23 '13 12:01

h4lc0n


2 Answers

You have to access like this.

e.touches[0].clientX/clientY.

the number touchs and touch information can be access via e.touches.

Take look at this FAQ.

How to get the x/y coordinates in touch events ?

here is the touch event documentation.

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

like image 96
BalaKrishnan웃 Avatar answered Sep 29 '22 07:09

BalaKrishnan웃


It is better to use getBoundingClientRect() method to calculate top & left values of an element.

The above approach, element.top, may not give top & left values relative to the viewport if the element is inside another container.

So to calculate touch co-ordinates relative to the element, we can do as below.

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

To find out more about getBoundingClientRect() method, click here.

like image 36
Venkat Avatar answered Sep 29 '22 08:09

Venkat