Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's .css() implementation

I was looking through the jQuery code and found this line:

elem.runtimeStyle.left = elem.currentStyle.left;

at

https://github.com/jquery/jquery/blob/449e099b97d823ed0252d8821880bc0e471701ea/src/css.js#L169

I am not sure why this is done. Isn't this useless?

Setting the runtimeStyle to the currentStyle would override nothing. Except make the runtimeStyle readable the next time you read it - which doesn't seem needed now.

I understand the overall concept here and why that code block exists (to convert numeric non-pixel values to the appropriate pixel value, by setting the left to the non-pixel value and reading its pixel value and then reverting the left back to the original value).

Edit See my answer below for why I think this is done (with jsFiddle illustration!).

like image 212
Aishwar Avatar asked Jul 06 '12 18:07

Aishwar


2 Answers

This is actually an IE hack where the value computed by the RHS of the above is feeded into the LHS of the above. ie.We are getting in new value so as to get the computed value out. Check out this blog to know more about it http://jsperf.com/testing-awesome-hack-for-ie

like image 134
Shiv Kumar Ganesh Avatar answered Sep 21 '22 17:09

Shiv Kumar Ganesh


I have been thinking about this. Here is why I believe it is done:

Setting the runtimeStyle to the currentStyle ensures that this is style that is applied on the element (the runtime style wins over the inline style). So when you set elem.style.left in the next line, there would be no change in the UI. However, the new pixel value can still be calculated using elem.style.pixelLeft - because this just converts the non-pixel value on the CSS to a pixel value. pixelLeft is not a measurement of the actual position, it is just a conversion to the pixel value.

See this: http://jsfiddle.net/RaSzc/

So this is done to figure out the pixel value without having anything change in the UI

like image 25
Aishwar Avatar answered Sep 19 '22 17:09

Aishwar