I need to be able to use jQuery to get the height of an image #imageHero
before it has fully loaded into the page. I then need to set the height of a div #imageDiv
to be the height of the #imageHero
which is being loaded.
I need this to happen ASAP when the page is created... currently the code I am using to set the div #imageDiv
to the height of the image #imageDiv
is happening to slowly and the page load looks odd...
Any suggestions?
To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.
As mentioned in the comments, this has already been answered here, although in pure JavaScript not JQuery. I have adapted that answer to:
Here's the function...
function getImageSize(img, callback){
img = $(img);
var wait = setInterval(function(){
var w = img.width(),
h = img.height();
if(w && h){
done(w, h);
}
}, 0);
var onLoad;
img.on('load', onLoad = function(){
done(img.width(), img.height());
});
var isDone = false;
function done(){
if(isDone){
return;
}
isDone = true;
clearInterval(wait);
img.off('load', onLoad);
callback.apply(this, arguments);
}
}
You can call the function with an image element, and a callback accepting width and height arguments...
getImageSize($('#imageHero'), function(width, height){
$('#imageDiv').height(height);
});
Fiddle - To see the full effect make sure the image is not in your cache (append a random to the image source).
An improvement on @Drahcir's answer, this version returns the true height and has other improvements. For testing change abc123
in image source to any random string to prevent caching.
There is a JSFiddle Demo as well.
<div id="info"></div>
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123">
<script>
getImageSize($('#image'), function(width, height) {
$('#info').text(width + ',' + height);
});
function getImageSize(img, callback) {
var $img = $(img);
var wait = setInterval(function() {
var w = $img[0].naturalWidth,
h = $img[0].naturalHeight;
if (w && h) {
clearInterval(wait);
callback.apply(this, [w, h]);
}
}, 30);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With