715 posts
  • Has sold $100+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
  • Located in 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
  • Has referred 50+ members
  • Has sold $40,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Had an item featured on Envato Market
+5 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
  • Has sold $100+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
  • Located in Belgium
+1 more
Hy-Studio says

Found it:

$(items).each(function(){ itemWidth += $(this).width(); });
5360 posts The Dude Abides
  • Located in United States
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $125,000+ on Envato Market
  • Has been part of the Envato Community for over 5 years
+9 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