Reputation: 1948
I need to get an image's dimensions in javascript (jQuery) when no styles are specified for it (jQuery's css() returns 0).
Maybe it is because I'm loading the image with jQuery just before asking for its dimensions. If this is the case, is there any event to listen that tells when the image has been loaded?
Upvotes: 4
Views: 8317
Reputation: 30384
Maybe the image has not fully loaded therefore the dimensions can not be given.But without your code I can't tell what you're doing wrong, but here is an Example that would work:
function LoadImage(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
}
else {
window.setTimeout('iLoad(imgsrc)', 1000);
}
}
<body onLoad='LoadImage(imgsrc)'>
Upvotes: 3
Reputation: 250
You can try to combine karim79's and John Boker's answer. Try to preload the image into hidden DOM and when it loads you can try to get its width&height.
Upvotes: 0
Reputation: 83729
here's a link that helps, look at the demo: http://docs.jquery.com/Events/load
with jquery there is a load() event that's fired when an image is done loading ie:
<script type="text/javascript">
$(document).ready(function()
{
$('#theImage').load(function()
{
// do the stuff here.
});
});
</script>
<img src="blah.jpg" id="theImage" />
Upvotes: 1
Reputation: 87440
You can use img's onload to get the dimensions once the image has loaded:
<img src="..." onload="getDimensions(this)" />
Upvotes: 0
Reputation: 36793
Depending on what you're after image.width or image.naturalWidth (and height equivalents) width/height gives the width/height attributes on the image tag, naturalWidth/Height gives the dimensions of the actual underlying image.
Upvotes: 0