Determine touch position on tablets with JavaScript

Tall83 picture Tall83 · Feb 2, 2017 · Viewed 7.7k times · Source

I have an 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 and 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.

How do I change the above code such that it works on tablets with "touchstart" instead of "mousedown"?

Answer

Christopher Reid picture Christopher Reid · Feb 2, 2017

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.