views:

31

answers:

4

if i have an image element where i'm not set height and width, like this

<img id="img" src="image.jpg" />

and then when i try to get

img_height = $("#img").attr("height");

it returns 0.

how can i get the size of image in google chrome.

Thanks

Update:

height = $("#img").height(); doesn't work too...

+2  A: 

You can use jQuery's .height() & .width()

EDIT: Now with caching to make the internet a better place:

var img_height, img_width, the_img = $("#img");

img_height = the_img.height();
img_width = the_img.width();
Stephen
+3  A: 

You can use the .height() and .width() methods, like this:

var height = $("#img").height();
var width= $("#img").width();

Also make sure you're running this in $(window).load() rather than $(document).ready() so that the image is loaded.

Nick Craver
it still returns `0`...
Syom
@Syom - Are you running it after the image is loaded?
Nick Craver
of course, i run it in `$(document).ready(...`
Syom
@Syom: He means `$(window).load()`, not `$(document).ready()`
Stephen
@Syom - That doesn't mean it's loaded :) see my answer above, you need to do this in `window.onload` when images are loaded. If you're creating the image dynamically, you'll need another approach.
Nick Craver
@Syom, the image is not loaded at `$(document).ready(...`, you need to run it at `$(document).load(...`)
kingjeffrey
@kingjeffrey - It has to be `window`, `document` has no load method ;)
Nick Craver
OOOPS. my bad:) Thanks all of you...
Syom
@Nick, yes, sorry: `$(window).load(...)`. Cut and Paste got the best of me.
kingjeffrey
A: 

Does this work in other browsers? Your HTML does not indicate a specified "height" attribute.

Andy
A: 

That returned 0 because the attribute 'height' is not set. Try this jQuery function instead:

img_height = $("#img").height();
Lekensteyn