Guys I\'ve been asking around and nobody can really tell me the benefits of using .css(‘width’)
and .css(‘height’)
rather than .width()
.width returns a unitless value, where as .css("width") returns the css value, width should be used with mathematical calculations
http://api.jquery.com/width/
var elH = someElement.height(); // 200
.height()
returns a Number, while
var elH = someElement.css("height"); // "200px"
above jQuery accesses the element's style
property like JS would in:
var height = someDOMelement.style.height; // "200px"
returning a String value in px
.
Yeap!
Main thing is, as most everyone told ".height() returns a unit-less pixel value".
But the question remains: Why is this so...?... Why was this thought this way?
@Jay Blanchard well said it: "The .height() method is recommended when an element's height needs to be used in a mathematical calculation."
So, if I may added, use "CSS" dim's everytime you deal with native stand-alone browser reactions - very handy to compute/react to elements disposition on a responsive window/div re-dimension process.
Use width() / height() to compute JQuery effect results, like hide()/show() inner layers (as you know won't affect CSS height
).
Note also that CSS height
property, for instance, does not include padding, border, or margin (you don't have inner X / outer X CSS dim's). So these must be computed.
Take a look at jQuery: Get height of hidden element in jQuery
Since this was the first hit in google when I was trying to remember the difference between the two, I thought I'd give a little more explanation with an example.
I have a div called myDiv like this:
border:1px solid black;
padding-right: 15px;
padding-left:15px;
margin-right:10px;
margin-left:10px
Console gives me this:
$('#myDiv').css('width') = 1100px;
$('#myDiv').width() = 1068;
1100 includes the 15 pixels for the right padding, the 15 pixels for the left padding, 2 pixels for the border(1 for each side) but NOT the margins. At least for me in chrome. 1068+15+15+1+1 = 1100
Yes, there is overhead for doing Number($('#myDiv').css('width').replace('px', ''))
but you only have to do it once each time. And you do have to cast the result as a Number, assuming that you want Number($('#myDiv').css('width').replace('px', '')) + 99
to be 1199. Otherwise you get 110099 as the answer.
they will also return/set different values (not talking about the 'px' suffix)
if you have box-sizing: border-box
see this example: http://jsbin.com/fugusixila/edit?html,css,js,console,output
By now people should know that one should be used for maths, and the other shouldn't...
Or should it?
I did a little speed test on the various options and according to my findings:
.css
.width
So in other words, to do a grab something and set another, you probably should:
$('#element1').width(parseInt($('#element2').css('width'), 10));