views:

37

answers:

3

I'm trying to access the width of certain elements by using jQuery's .width() function, but sometimes the return value is 0 when I don't expect it. Is this a known issue? Does an element have to be visible for this to work, perhaps? If there are limitations, how can I work around them?

+1  A: 

The element has to have loaded.. try binding it on window load

$(window).load(function(){  alert('#img').width()   });

You can also try explicitly defining a width through css on the element I guess.

meder
+6  A: 

If you're dealing with images, make sure to run the code in $(window).load() rather than $(document).ready(), like this:

$(window).load(function() {
  var width = $("img").width();
});

Otherwise, make sure the element is visible, hidden elements have no .width() or .height() (it'll return 0 for both).

Nick Craver
Would you suggest making the element in question visible before getting the width and then re-hiding it? Or is there a better workaround?
Pieter
@Pieter - You can give it a relative position way off the page, or just show/hide it...remember that JavaScript has to pause for the UI thread to update, so the user won't see a blink when you do this :)
Nick Craver
I chose to set `display` to `block` but keeping `visibility` set to `hidden` so that I can get the width without risking that the user can see the element even for a split second.
Pieter
A: 

Hi, You can check if image is visible with this extra condition

$(window).load(function(){  if($("#img").is(":visible"))alert('#img').width()   });
Kapil