I just realised there is a difference between
<foo>.css('marginTop')
(which I thought is the standard jquery-notation) and
<foo>.css('margin-top')
(which I thought was non-standard).
If has margin-top: 3em; (for example), the first notation gives me 3em, the second notation gives me 48px (which is 3em in Pixels).
I like this behaviour but I could not find anything about it in the API (or am I blind?)
Why is this the case and where can I find information about it?
P.S.: Just to be precise: of course other attributes but margin-top work aswell…
Thank you!
The doc says “jQuery can equally interpret the CSS and DOM formatting of multiple-word properties”, but in reality it is doing that through rough and ready hacks which don’t always behave predictably.
In particular, if you supply a DOM-style
camelCaseName, it will first try to access the inline style declaration asstyle.camelCaseName. Then if that fails (typically because the style was not set inline), it falls back to tryinggetComputedStylewith thecamelCaseNameconverted tohyphen-separated-name(*). The computed style is not the same thing as the declared style: the browser can resolve various relative declarations in a computed style, such as converting lengths to pixel units.However, the reverse does not hold! If you supply a CSS-style
hyphen-separated-name, it jumps straight to the computed style(*) code without trying to convert tocamelCaseNameand look at the inline style.I don’t think I’d want to rely on this behaviour… it smells a little bit buggy to me. If you can keep the inline style declaration off the element you want to measure, you should be able to ensure you always get the computed style back regardless of which name type you use. But then again, jQuery doesn’t give you that as a documented promise. Such is the nature of trying to hide a complicated model behind a seemingly-simple “Do What I Mean” interface.
(*): except in IE where there is no
getComputedStylefunction, so it falls back to a weird and fragile mix ofcurrentStyle,runtimeStyleand document alteration to try to get a computed style out.