tags:

views:

1467

answers:

3

When I run following code:

  node = $('.period')
  alert(node.width() + ' ' + node.css('width'))

i get '0 144px'. How is that possible?

+12  A: 

Maybe you're calling it on $(document).ready, and as width() Gets the current computed, pixel, width of the first matched element., it'd be 0 as it has not been rendered yet...
css('width') however reads from the css stylesheet, which would be already available.

x3ro
I think this is right! I called it as a click and it computed correctly.
skybondsor
Does it apply to tab loading (I am using jquery ui tabs, not document ready) too? It seems so, but I would like to get sure.
gruszczy
I've actually never used jQuery UI. You could easily find out by trying to get the value at a later time (onClick for example).
x3ro
If you want to be sure everything is loaded, you can use $(window).load
jeroen
A: 

I found a similar behavior.

var div = $('<div></div>').width(200).appendTo($(".div1")[0]);
 div.width() // return 200
 div.css("width") // return 200px

But when I remove append statement I get the following:

var div = $('<div></div>').width(200);
 div.width() // return 0
 div.css("width") // return 200px

How is that possible?

Irina
A: 

This should have been a comment to Irina's post, but I don't have 'comment' authority yet.

(Is there a better way to do this in the future?)

To quote x3ro's earlier answer:

as width() Gets the current computed, pixel, width of the first matched element., it'd be 0 as it has not been rendered yet...

In your case, this applies to div.width() in your second example, since this div has not yet been rendered (or even been added to the DOM at all), thus it will always return 0.

To continue quoting x3ro's answer:

css('width') however reads from the css stylesheet, which would be already available.

Which is why div.css('width') works as expected, since .width(200) would add the width value to the css.

Brad