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?
views:
37answers:
3
+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
2010-07-18 12:08:25
+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
2010-07-18 12:08:32
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
2010-07-18 12:13:52
@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
2010-07-18 12:16:26
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
2010-07-18 14:59:31
A:
Hi, You can check if image is visible with this extra condition
$(window).load(function(){ if($("#img").is(":visible"))alert('#img').width() });
Kapil
2010-07-18 13:55:23