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>
kylex
  • 14,178
  • 33
  • 114
  • 175
  • possible duplicate of http://stackoverflow.com/questions/1100503/how-to-get-just-numeric-part-of-css-property-with-jquery – qbolec Oct 29 '15 at 17:16

2 Answers2

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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 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 '13 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.

konrad.kruczynski
  • 46,413
  • 6
  • 36
  • 47