14

This code works in FF, but not in IE:

parseInt($('.scroller').css('left');

In FF it returns 0px;

In IE it returns NaN.

What's a good way to get a pixel position of an element?

<div class="holder">
    <div class="scroller">
    </div>
</div>
1

2 Answers 2

28

Use offset:

$('.scroller').offset().left;

offset() returns an object containing the properties left and top, which are the position values relative to the document in pixels.

If you want the position relative to the parent element, use position instead.

1
  • 3
    It does seem that there are cases where neither offset() nor position() give the desired value. I have a relatively positioned element and in my case, offset() and position() both return the same value and it is different from $('element').css('left'). It is the css left value that I need. For now I am using parseInt($('.element').css('left').replace('px', '')). I suspect the reason why IE chocked on kylex's attempt is that it has 'px' on the end. Stripping that off seems to play well with IE. Does anyone know of a better way to do this in this case?
    – Jim Cooper
    Jan 15, 2013 at 15:44
0

It would be however always relative to document, therefore position() (relative to parent, i.e. holder) would sometimes be rather accurate and sometimes none of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.