Reputation: 113
I'm trying to get the width and height of an image inside of a ul li a as followed:
<ul class="gallery">
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
</ul>
I've done this jquery code as followed:
$(document).ready(function(){
$(".gallery").find("li a").each(function() {
alert($(this).find("img").width() + 'x' + $(this).find("img").height());
});
});
and for some reason I keep getting 0x0, all I want is the width and height of each of the image inside the ul li a.
I've also read that I need to do the following:
$('.gallery li a img').load(function() {
var $img = $(this);
$img.parent().width($img.width());
});
because the document.ready is fired before the image.load, but It still not working.
Any help will be appreciated. Thank you.
Upvotes: 0
Views: 729
Reputation: 191749
$(".gallery img").on("load", function () {
var $this = $(this);
console.log($this.width() + "x" + $this.height());
}).each(function () {
if (this.complete) {
$(this).trigger("load");
}
});
Upvotes: 1
Reputation: 207901
You should be able to do this within the window.load event:
$(window).load(function(){
$(".gallery").find("li a").each(function () {
console.log($(this).find("img").width() + 'x' + $(this).find("img").height());
});
});
See the difference between window.load and document.ready here: window.onload vs $(document).ready()
Upvotes: 1