Question

I am currently trying to track the x and y locations of an image on my page animated with the Zepto .anim() method. The problem is that any methods I use to try to find these only return the location of where it was initially loaded, not the location that it is at now. I can work around that by calculating where it is whenever I need that, but that method is a bit unreliable. Does anyone know of a simple way to do this?

Edit: As requested:

$('#circle').anim({translateX: newX + 'px', translateY: newY + 'px'}, speed, 'linear')
Was it helpful?

Solution

This is going to be a little complicated because you are using CSS3 transforms and there is not really any Zepto API exposed for retrieving this information.

First you have to understand where the information is stored. Assuming you're on Android, iPhone, Safari, or Chrome, this is the webkitTransform property.

If you access $('#circle').css('webkitTransform'), you will see translateX(somevalue) translateY(somevalue) where the values are what you passed through in the JavaScript.

Unfortunately, this is the final value and not the intermediate value. For the intermediate value, you will need something like this:

getComputedStyle($('#circle')[0]).webkitTransform
// == "matrix(1, 0, 0, 1, 87.66703796386719, 82.89203643798828)"

These values are stored in a transformation matrix. It can be either a matrix or a matrix3d based on what was passed. See my answer to another SO question on how to extract X and Y values from this string.

Obviously, this is a lot of work and you will need to add more logic for mobile Firefox and such. You may want to consider what it is you're attempting and see if there is an alternative approach.

OTHER TIPS

Code from : Retrieve the position (X,Y) of an HTML element

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left; 

You can use it to accurately get the current position of the element on the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top