0

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.

onlymushu
  • 111
  • 2
  • 13
  • 1
    Well, I'm guessing it's zero because you haven't got a filename in `src` - no image is loaded yet. – Andy Sep 15 '13 at 20:52
  • Working fine for me. http://jsfiddle.net/fEQWK/ Check whether image is loading or not. – Kiran Sep 15 '13 at 20:54

2 Answers2

1

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()

jsFiddle example

Community
  • 1
  • 1
j08691
  • 204,283
  • 31
  • 260
  • 272
  • I find was the problem and your answer help me discover what it was. I was doing my script before the image were load and Andy mention in a comment. Your sold works quite find I won't have to move my script at the bottom of the page. Thanks – onlymushu Sep 15 '13 at 20:59
1
$(".gallery img").on("load", function () {
    var $this = $(this);
    console.log($this.width() + "x" + $this.height());
}).each(function () {
    if (this.complete) {
        $(this).trigger("load");
    }
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • I chose to upvote this because it will return faster than waiting for window.onload. Future SO'ers, this is the most responsive solution so far. – Jordan Sep 15 '13 at 21:03