jelm
jelm

Reputation: 39

Get image width of images in divs with jquery

Is it possible to get the width of all images the divs and then set #content css to that value with jquery? Im using a horizontal layout for a project and need to add images from time to time.

<div id="content">
  <div class="entry">
    image
    image
  </div>
 <div class="entry">
    image
    image
 </div>
</div>

Upvotes: 0

Views: 905

Answers (3)

corymathews
corymathews

Reputation: 12619

Building off of @Bob's answer. I have not tried it but it would seem to me that the .width() function would not take into account padding and margin. If it does then you only need the .width() otherwise something like below.

width = 0;
$.each(jQuery('.entry'), function(i, e) {
    width += $(e).width() 
          + $(e).css("margin-left") + $(e).css("margin-right") 
          + $(e).css("padding-left") + $(e).css("padding-left");
});
$('#content').width(width);

Upvotes: 1

Bob
Bob

Reputation: 1182

Maybe you can try

var width = 0;
$.each(jQuery('img'), function(i, img) {
    width += $(img).width();
});
$('#content').width(width);

Upvotes: 2

Stephen Wrighton
Stephen Wrighton

Reputation: 37819

The only way that comes to mind would be to read the contents of the CONTENT div, find every IMG tag, and get its associated width (while keeping a running total) and then assign the CONTENT div's width to the total.

Upvotes: 0

Related Questions