fufu
fufu

Reputation: 99

How to get height of a 100% width image with auto height?

In this case, I set an image with width: 100% and height: auto (actual image size is 362x614). I need to get height of image for another step.

Here is my code:

<img class="phone" src="img/phone2.png">

and js:

$(document).ready(function() {
   phoneSlider();
});

$(window).resize(function(){
   phoneSlider()
});

function phoneSlider(){
   var phoneMaskWidth = $(".phone").width();
   var phoneMaskHeight = $(".phone").height();
       console.log(phoneMaskWidth + "|" + phoneMaskHeight);
       .......
}

Then, I check in the console, and the result: 362|0. Why is phoneMaskHeight showing 0 and how can I get the real height?

Upvotes: 0

Views: 1676

Answers (5)

Salman Arshad
Salman Arshad

Reputation: 272006

Move your code from $(document).ready() to $(window).load(). The browser needs to load the image (or at least the image header) before it can calculate its width and height. Document ready event can fire before the browser has chance to have a look at the image.

Demo here; change the image source (or empty browser cache), run and look at the console

Upvotes: 2

uihelp
uihelp

Reputation: 198

$(document).ready(function(){
console.log($('#myimg').width() + 'x' + $('#myimg').height());

console.log($("#myimg").attr('src'));

})

working demo [http://jsfiddle.net/A5QJM/238/]

Upvotes: 0

edzhelyov
edzhelyov

Reputation: 399

Browsers load images asynchronously and until the image is fully loaded its height will be unknown.

As others have suggested you will need to attach your code to the "onload" event that is fired when the image is loaded, but that will force you to change your whole phoneSlider method. You will need to put everything that depends on the height of the image in the corresponding onload callback.

If you don't need to do your calculation as soon as the image is loaded, the Salman A's answer is the better approach - put your logic when the window#onload event is fired, this ensures all external resources (including images) are loaded.

Upvotes: 0

Lijo
Lijo

Reputation: 6778

$("img.phone").on('load', function() { alert( this.height ); });

This worked for me.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

use:

var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = $(".phone").attr('src');

Working Fiddle

Upvotes: 2

Related Questions