Reputation: 10681
I have a set of images that are responsive to the page (i.e. max-width set to 100% ).
<div class="exh">
<img src="#" />
</div>
<div class="exh">
<img src="#" />
</div>
<div class="exh">
<img src="#" />
</div>
with
.exh img {
max-width:100%;
}
How do I retrieve the height of the image after the window is resized and whenever the page is loaded? When I use the following, I get a height of 0.
$(".exh img").each(function() {
var $this = $(this);
console.log( $this.height() );
});
Upvotes: 1
Views: 10075
Reputation: 2134
per this answer I gave to a similar question :
Why does jQuery.css('width') return different values in different browsers?
.width()
or height()
is the "rendered in the DOM" size of the element - and for it to return a value greater than 0, the element needs to be fully available to the DOM ( aka the image needs to be fully loaded )
What you want is :
var myImage= new Image();
myImage.onload=function() { alert(this.height);}
myImage.src= "your/image/url";
In short - you need to guarantee that the image has loaded before you call height()
Upvotes: 2
Reputation: 4588
If you need to do it whenever the page is loaded and when the page is resized do this:
$(document).ready( function() { //Fires when DOM is loaded
getImageSizes();
$(window).resize(function() { //Fires when window is resized
getImageSizes();
});
});
function getImageSizes() {
$(".exh img").each(function() {
var $this = $(this);
console.log( $this.height() );
});
}
More Info on .resize(): http://api.jquery.com/resize/
More Info on .ready(): http://api.jquery.com/ready/
Upvotes: 5