715 posts
  • Exclusive Author
  • Sold between 100 and 1 000 dollars
  • Belgium
  • Has been a member for 5-6 years
  • Bought between 10 and 49 items
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
  • Has been a member for 6-7 years
  • Won a Competition
  • Sold between 50 000 and 100 000 dollars
  • Bought between 10 and 49 items
  • Referred between 50 and 99 users
  • Exclusive Author
  • Romania
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
  • Exclusive Author
  • Sold between 100 and 1 000 dollars
  • Belgium
  • Has been a member for 5-6 years
  • Bought between 10 and 49 items
Hy-Studio says

Found it:

$(items).each(function(){ itemWidth += $(this).width(); });
5313 posts The Dude Abides
  • United States
  • Exclusive Author
  • Has been a member for 5-6 years
  • Elite Author
  • Bought between 100 and 499 items
  • Referred between 100 and 199 users
  • Author had a Free File of the Month
+5 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