views:

64

answers:

3

Here is a test case/live example. Summary of problem:

This only works in WebKit:

Y.one('#container').setStyle('margin-top', 100);

This works in all browsers:

Y.one('#container').setStyle('margin', 100);

Why does setting margin-top work only in WebKit?

EDIT: the fix is shown below in one of the answers. You need to have marginTop here, and then it works. So, the edited question is, WHY do you need marginTop and not margin-top in this case?

+1  A: 

This is working for me in firefox:

<div id="nav">
<a href='#' onclick='document.getElementById("nav").style.marginTop="25px";'>test</a>
</div>
Robert
And I can confirm IE as well.
Robert
This is almost the answer. I'd also like some W3C reference or something that points to this marginTop vs margin-top stuff. Anyone? :)
Jaanus
http://www.w3schools.com/css/pr_margin-top.aspScroll down, it tells you to access with javascript as "object.style.marginTop="10px"
Robert
I understand that, but it's not explaining the root cause, WHY does the inline syntax need marginTop and not margin-top (especially if you are setting it in the way that I have shown so you are not bound by JS variable name constraints that cannot have a dash).
Jaanus
Awesome, glad I could answer your question yet not get credit taking the time to answer it for you. Cheers.
Robert
Sorry, you're right.
Jaanus
+1  A: 

It has to be marginTop, because you are not setting a CSS property in a CSS file. You are setting the marginTop property of the style object. - is an invalid character for an identifier.

Strelok
So the only mystery remaining is, why was it working with Webkit?
Jaanus
+1  A: 

If you are accessing the style property, then by the standard camel case applies. So if webkit supports smth like element.style["margin-top"] then it's a quirk. Remember that you are not dealing directly with CSS here, it's just an intermediate layer.

In short - marginTop is part of CSS2Properties interface but margin-top is not.

Some libraries tend to convert the property names automatically, i.e. Prototype that converts all hyphenized property names into their camel case forms, so you don't need to worry about it.

Andris
I don't know why camel case is the only way (as it is totally possible, proven by WebKit), at least I have no references to *official sources*. Flanagan's *JavaScript Definitive Guide* (p. 372) states that - Many CSS style attributes, such as font-family, contain hyphens in their names. In JavaScript, a hyphen is interpreted as a minus sign, so it is not possible to write an expression like `element.style.font-family = "sans-serif"` [...] the property name is formed by removing the hyphens and capitalizing the letter immediatelly following each hyphen.
Andris