1

I'm trying to get x and y coordinates of mouse click event within the relative container. There are already several question on this topic on stackoverflow, for example jQuery get mouse position within an element So I've tried to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent as it was in the example:

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});

In most cases it works just fine. But it does not work on Android (Nexus 5) in Chrome WHEN we scroll content. It also does not work in Desktop Chrome in emulation mode. The value of pageY is strange and I do not understand why. Could someone help me with that? Maybe we can't use this approach? Or there is a quick fix for that?

Here is the Plunk: http://plnkr.co/edit/Ul2bd8v1iLRvEyGxjv4b?p=info Just scroll to the red rectangle and click on it. It would output the coordinates of mouse relative to the top left corner of that rectangle. If you turn on emulation in Chrome (Nexus 5 for example) or open that Plunk on Android device in Chrome (tried v. 4.4.2 and 4.2.2, ONLY Chrome) you will get an incorrect position.

Thanks in advance!

Community
  • 1
  • 1
Andrey
  • 5,906
  • 4
  • 24
  • 30

1 Answers1

3

I am not expert in creating layouts for mobile devices, so please be gentle and check if my solution fits your needs. I think that the main issue that for mobile devices you should use touch events instead of click event. So you may use touchstart instead of click event. I've changed your example a little bit:

I've added one more subscription for touchstart event:

$('.container').on('touchstart', handler);

I've changed your handler to handle touch events as well:

var touch = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0];
e = touch || e;

Complete example your may find here: http://plnkr.co/edit/whze0Idf24NMvo1RCe7T?p=info I've checked it in usual chrome and in emulator as well, it seems that it works ok.

So, the basic idea to use touch events on mobile devices. Probably you need to improve subscription action to subscribe only to one event, but it's up to you.

UPDATED:

After some research I've found this thread: Did Android chrome pageY value change with the latest chrome update?

The problem is with specific version of Chrome (38.0.2125.102), bug was reported here: https://code.google.com/p/chromium/issues/detail?id=423802

Community
  • 1
  • 1
ntl
  • 1,289
  • 1
  • 10
  • 16