I have problems with getting the relative position of a touch event to the html element on which it occurred. I know, this was probably asked a million times. But I am struggling with this one for days, and looked at many solutions.
Strange thing, on all desktop browser I tested, it worked, but on none mobile browser.
I tested on Desktop
- Opera
- Chrome
- Firefox
and on Mobile
- HTC One X (4.1) Chrome
- Samsung Note 10.1 (4.1) Stock Browser
- Samsung Note 10.1 (4.1) Chrome
- Nexus 7 (4.2) Chrome
Here is a jsfiddle with my code.
It seems as the problem is, that if my canvas which captures the events is inside a scrolling area, the scrollTop
property of a offsetParent
element is set to 0
on the mobile browser, where it has the appropriate value on the desktop browsers.
So is this a known bug? Or did I oversee something here? And more important, is there a workaround, or another method to achieve my goal?
Here is some code of mine, how I calculate the relative position:
getRelativePosition: function (element, event ) {
var position = { x : event.pageX, y : event.pageY };
do {
this.log(element.offsetTop);
this.log(element.offsetHeight);
position.x -= element.offsetLeft;
position.y -= element.offsetTop;
position.x += element.scrollLeft;
position.y += element.scrollTop;
} while(element = element.offsetParent);
return position;
}