Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery .css('left') and .position().left return different values?

The values I'm getting for $(el).css('left') and $(el).position().left are different?

If I go $(el).css('left', '100px'), then $(el).css('left') it returns 110px instead of 100px (yes, it is always 10% more) and if I evaluate $(el).position().left, it gives me 100.

Why does Chrome behave this way? You can see how this would affect jQuery animations using the left property.

I'm using Chrome 21.0.1180.57 on Ubuntu.

EDIT 1: Seems to be only affecting Chrome, FF 14.0.1 is giving me the same values.

like image 645
Gaurav Dadhania Avatar asked Aug 08 '12 07:08

Gaurav Dadhania


People also ask

What is the difference between position and offset in jQuery?

The offset() method in jQuery returns the first found position of HTML element with respect to the document. The position() method in jQuery returns the current position of HTML element with respect to its offset parent. The jQuery UI offset() is relative to the document.

How to get position using jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How to set style property in jQuery?

The css() method in JQuery is used to change the style property of the selected element. The css() in JQuery can be used in different ways. Return value: It will return the value of the property for the selected element.

What does CSS left do?

The left CSS property participates in specifying the horizontal position of a positioned element. It has no effect on non-positioned elements.


2 Answers

The left returns calculated value of the CSS left property.

position().left returns the x-coordinate relative to the element's first offset parent.

These values can be equal and they can be not equal .

position().left can also easily be different between browsers because of different rendering whereas .css("left") can only differ in the units given, if that.

like image 69
Esailija Avatar answered Sep 27 '22 19:09

Esailija


Try this code :

$("#div")[0].style.left
like image 36
Gabriel Silveira Avatar answered Sep 27 '22 17:09

Gabriel Silveira