0

I am trying to get the position of an element (password input) on the webpage http://login.secureserver.net/index.php?app=wbe . I type this code in the javascript console in Chrome

function fp(obj){
    var x=0,y= 0;
    if (obj.offsetParent) {
        do {
            x+= obj.offsetLeft;
            y+= obj.offsetTop;
           } while (obj = obj.offsetParent);
    }
};
fp(document.getElementById('password'));
console.log("x="+x+"; y="+y)

and it returns x=809; y=380.

When measuring the screenshot with photoshop it appears to have x=816; y=388.

So what's the problem and why it is not returning the real distance?

Idrizi.A
  • 9,819
  • 11
  • 47
  • 88
  • what is your object? maybe it is an image which has width and height that you are not consider it! – Armen Jul 29 '13 at 23:24
  • it's a password input – Idrizi.A Jul 29 '13 at 23:25
  • My guess would be that it has something to do with the css style of one of the involved elements. You could try to use `element.getBoundingClientRect();` as suggested here: http://stackoverflow.com/questions/442404/dynamically-retrieve-the-position-x-y-of-an-html-element Maybe this will lead to a different result? – basilikum Jul 29 '13 at 23:40
  • you `var` your `x` and `y` in your _function_ but don't return them – Paul S. Jul 29 '13 at 23:46
  • @basilikum it is working now. Please provide an answer so I can accept it. – Idrizi.A Jul 29 '13 at 23:51
  • if you are getting x=809; y=380 and expect x=816; y=388 i would think there are some borders involve.. – gezzuzz Jul 29 '13 at 23:52
  • @gezzuzz element.getBoundingClientRect(); is working just perfectly. – Idrizi.A Jul 29 '13 at 23:53

1 Answers1

0

You included the tag jQuery in your question, so I assume you are already using it.

I'd recommend using the function .position() for this, which should return the X and the Y coordinates of your password input:

var p = $('#password').position();
console.log("x=" + p.left + "; y=" + p.top);

If you are not using jQuery, element.getBoundingClientRect() is fine, but it doesn't have the cross-browser fixes jQuery provides.

federico-t
  • 12,014
  • 19
  • 67
  • 111