tags:

views:

46

answers:

2

Could someone explain what's wrong with this snippet?

I'm looking to get the width of all images in a div.

var totalwidth = $("#imagecontainer > img").width();
$("#imagecontainer").width(totalwidth);

sorry, thought it was just a syntax problem (un)working example here:
http://jsfiddle.net/TZ2nT/3/
the container div does not accept the value for some reason?

+3  A: 

did u tried this

var width = $("#imagecontainer  img:first").width();
var totalWidth = width * $("#imagecontainer  img").length;
console.log(totalWidth);

Edit :

$(function() {
  var totalwidth = 0;
  var arey = [];
  $('#imagecontainer img').each(function() {
    var width = $(this).width();
    width = parseInt(width);
    arey.push(width);
  });

  for(var i in arey) {
   totalwidth +=arey[i];
  }
  $('#imagecontainer').width(totalwidth);
  $('#readout').html(totalwidth);
});

Test it here http://jsbin.com/ayira3

Ninja Dude
Wow thanks. I know this is not what I asked for but it's what I was looking for. Cheers!
jack
@jack you're welcome pal =)
Ninja Dude
+1 - Nice one. :o)
patrick dw
+1  A: 

You haven't really described what is wrong, but I'm guessing you're running the code before the image has been fully downloaded, so it doesn't yet have a width.

If that's the case, try this:

$("#imagecontainer > img").load(function() {
    var $th = $(this);
    $th.parent().width( $th.width() );
});

Remember that jQuery's .ready() method does not wait for images to load. You can use the load() method agains the <img> element instead. This way the code will not run until you actually have an image.

If you ever need to run code after all images have loaded, you can use:

$(window).load(function() {...
patrick dw
thanks but i can get and pass the value elsewhere though (see example), so i don't think that's the problem.
jack
@jack - In the example you posted, the imagecontainer is getting the width. So what is it not doing for you?
patrick dw
I modified your example slightly and it's working for me. http://jsfiddle.net/TZ2nT/4/ outputs `782 vs 782` for me.
Robert
@jack if want to cache the total width of the images, you need to sum up the individual width. `$("#imagecontainer > img").width();` this won't give you the total width
Ninja Dude
ah how stupid, i wanted the width of all the images, didn't notice that the value was only for one image! thanks for pointing this out.
jack