715 posts
  • Author Level 2
  • Collector Level 2
  • Exclusive Author
  • Belgium
+1 more
Hy-Studio
says

Hi,

Here’s a simple question for you Javascript guru’s :).

Here’s the thing, I have a ul list in which every li tag has an image. (don’t know how many li items with images there can be, it’s dynamic).

Now I want to know the width of the image (which should all be the same but you never know).

So I have my code here:

$(items).each(function(){ itemWidth = $(this).width(); totalWidth += itemWidth; }); console.log("totalWidth: ", totalWidth);

items is the var where I get the images. So I don’t think that this code will work and it doesn’t :).

If anyone can help me out here?

Thanks!

3072 posts
  • Affiliate Level 3
  • Author Level 6
  • Collector Level 2
  • Weekly Top Seller
+7 more
wickedpixel
says

Before reading the size of an image, it needs first to be loaded and to be visible. Working with a size generated by loaded images can be pretty hard. I guess you will have to listen to the loading event to read those widths.

715 posts
  • Author Level 2
  • Collector Level 2
  • Exclusive Author
  • Belgium
+1 more
Hy-Studio
says

Found it:

$(items).each(function(){ itemWidth += $(this).width(); });
5467 posts The Dude Abides
  • Top Monthly Author
  • Trendsetter
  • Weekly Top Seller
  • United States
+13 more
CodingJack
says

Found it: $(items).each(function(){ itemWidth += $(this).width(); });

You can read the image’s “width” attribute with a fallback to $this.width() which might be more reliable:

var $this, img;

$(items).each(function(){

    $this = $(this);
    img = $this.children("img");

    if(img.length) {

        itemWidth += parseInt(img.attr("width"), 10) || $this.width();

    }
    else {

        itemWidth += $this.width();

    }

});
by
by
by
by
by
by