Monday, May 14, 2012

Javascript: Calculate width of div as sum of images

Basically, I need "style="width:__" to be added to the "img-container' div, with the width being the sum of all the images and their padding. The images and image widths are added in dynamically through a CMS, which is why I need the javascript to calculate the width dynamically.



<div id='img-container'[HERE IS WHERE I NEED THE WIDTH TO BE ADDED]>
<div class='picture_holder' >
<div class='picture' >
<img src="{image}" style='width:{width}px;padding-right:10px;'/>
<div class='captioning'>{caption}</div>
</div>
</div>
</div>


I don't know javascript at all, but tried to piece something together (I didn't even get to adding in the padding yet):



<script type="text/javascript">
var $name = ('div#img-container');
var Imgs = div.getElementsByTagName('img');
var w = 0;
for ( var i = 0; i < Imgs.length; i++ ){
w += parseInt(Imgs[i].offsetWidth);
}
</script>


It's obviously not working at all though. Any help would be much appreciated!





No comments:

Post a Comment