Search code examples
javascripttouch-event

How to get x-coordinate of a touch event point relative to the target element?


So I have an image that looks like this:

var elem = document.getElementById("bt");
elem.addEventListener("touchstart", handleStart, false);

function handleStart(e) {
  e.preventDefault();
  var touch = e.targetTouches[0];
  X = touch.pageX;
  Y = touch.pageY;
  return [X, Y];
}
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/142996/sections-3.jpg" id="bt" width="900" height="600">

What I want to do, is get the x- and y-coordinates of a touch event relative to the image itself.


Solution

  • You can achieve that easily using Jquery.In my code I am showing using click event since i am using desktop but you can replace click by touch event.

    FIDDLE

    Here is the code:

    $('.clickable').bind('click', function(ev) {
      var $div = $(ev.target);
      var $display = $div.find('.display');
    
      var offset = $div.offset();
      var x = ev.clientX - offset.left;
      var y = ev.clientY - offset.top;
    
      $display.text('x: ' + x + ', y: ' + y);
    });
    .clickable {
      border: 1px solid #333;
      background: #eee;
      height: 200px;
      width: 200px;
      margin: 15px;
      position: absolute;
    }
    
    .display {
      display: block;
      height: 16px;
      position: absolute;
      text-align: center;
      vertical-align: middle;
      width: 100%;
      top: 50%;
      margin-top: -8px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='clickable'>
      <span class='display'></span>
    </div>