Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return X and Y coordinates when using jquery.hammer.js

I am programming a little page using jquery.hammer.js and I have having problems getting the x and y coordinates of a touch event.

my code is as follows:

var x1, y1;
var element = document.getElementById("myDIV")
$(element).hammer().on("touch", function(e){
x1 = e.clientX
y1 = e.clientY

document.getElementById("resultDIV").innerHTML = x1 + " " + y1
}

but all I get is "undefined undefined" as my result.

i have everything i can think of, any help is much appreciated.

like image 272
DFania Avatar asked Nov 29 '22 12:11

DFania


2 Answers

e.gesture is deprecated now. With the latest version of Hammer.js, you should use

var tapX, tapY;
tapX = e.center.x;
tapY = e.center.y;
like image 197
hudidit Avatar answered Dec 10 '22 17:12

hudidit


  1. You've missed ); at the end.
  2. Try to always use semicolons (;) in the end of each statement.
  3. If you're starting to use some library, read the documentation and how-to section first.

You can find the information you want from the documentation on GitHub.

Update:
I've analyzed the event object and found the gesture property of this object. The gesture contains another property, which is called center. And finally you can get the X and Y coordinates from this property by using pageX and pageY.

var x1, y1;
x1 = e.gesture.center.pageX;
y1 = e.gesture.center.pageY;

Here is the working demo of your example in JSFiddle.

And also if you use multi-touch, you can get the coordinates of each touch by using the touches array of gesture property. The other property names remain the same (pageX, pageY).

var x1, y1;
x1 = e.gesture.touches[0].pageX;
y1 = e.gesture.touches[0].pageY;

Here is the second demo of your example using touches array to get coordinates for only the first touch.

like image 21
Karlen Kishmiryan Avatar answered Dec 10 '22 17:12

Karlen Kishmiryan