Tall83 Tall83 - 4 years ago 142
Javascript Question

Determine touch position on tablets with JavaScript

I have the following problem: I have some object (with the name "element").
If somebody touches the tablet, I would like to return the x- and y-coordinates of the touch position relative to the object (i.e. the upper left corner of the object has the coordinates x=0, y=0).

I know how to implement this on desktops:

$(function() {
$(document).mousedown(function(e) {
var offset = $("#element").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert(relativeX+':'+relativeY);
$(".position").val("afaf");
});
});


So the word "mousedown" should be replaced by "touchstart", I guess. However, it still doesn't work.

Could somebody help me and change the code of above such that it works on tablets with "touchstart" instead of "mousedown"?

Thank you very much in advance for any help!

Answer Source

You have to explicitly pull a touches object out of the event, it doesn't contain the coordinates directly. Look at line two of the code below.

Here is the code I always use to get touch/pointer coordinates:

    if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
        var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
        x = touch.pageX;
        y = touch.pageY;
    } else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
        x = e.clientX;
        y = e.clientY;
    }

Put this inside an event listener that listens for any or all of those events and add your offset calculation and this should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download