jQuery.css() - marginLeft vs. margin-left?
With jQuery.css() I've been told I can use the following two functions for the same results:
$(".element").css("marginLeft") = "200px";
$(".element").css("margin-left") = "200px";
I've always used marginLeft
as this is what is used in the documentation:
http://api.jquery.com/css/
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
Why has jQuery allowed for marginLeft
as well as margin-left
? It seems pointless and uses more resources to be converted to the CSS margin-left
?
jQuery's underlying code passes these strings to the DOM, which allows you to specify the CSS property name or the DOM property name in a very similar way:
element.style.marginLeft = "10px";
is equivalent to:
element.style["margin-left"] = "10px";
Why has jQuery allowed for marginLeft as well as margin-left? It seems pointless and uses more resources to be converted to the CSS margin-left?
jQuery's not really doing anything special. It may alter or proxy some strings that you pass to .css()
, but in reality there was no work put in from the jQuery team to allow either string to be passed. There's no extra resources used because the DOM does the work.
I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...
$(".element").css( { marginLeft : "200px", marginRight : "200px" } );
as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...
$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );
without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.
EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];