Hammer.js: How to calculate target element relative position clicked?

Created on 26 Jun 2014  路  2Comments  路  Source: hammerjs/hammer.js

If the clicked element is 50px width and centered on the page that is 1000px wide, I would like to get back 25px and not 500px if I tap the center of the element.

At first blush this appears to be simple with simple math and using pageX and the elements offsetLeft. However, after a bit of testing and reading I appears there are a few cross-browser issues with nested padding and borders that can throw off the calculation.

Someone must have had this challenge before?

UDPATE -
Not even the default $event.gesture.touches[0].pageX works.
It returns a number that is shorter then the distance to the left edge of the document.

Most helpful comment

+1

Here is how I solved for now:

var bb = e.target.getBoundingClientRect();
// Correct, but will not work with touch.
var position = {
    x: e.pointers[0].layerX,
    y: e.pointers[0].layerY,
}
// Correct and works with touch.
var position2 = {
    x: e.center.x - bb.left,
    y: e.center.y - bb.top,
}

Be careful that getBoundingClientRect is slower than offset. more

All 2 comments

+1

Here is how I solved for now:

var bb = e.target.getBoundingClientRect();
// Correct, but will not work with touch.
var position = {
    x: e.pointers[0].layerX,
    y: e.pointers[0].layerY,
}
// Correct and works with touch.
var position2 = {
    x: e.center.x - bb.left,
    y: e.center.y - bb.top,
}

Be careful that getBoundingClientRect is slower than offset. more

Closing in favor of #806 or custom solutions.

Was this page helpful?
0 / 5 - 0 ratings