Calculate the width of an element when its children elements are loaded dynamically

Recently, while working on a project I came across the need to adjust the width attribute of an element with javascript. Simple task, I know, but this element had its children elements being loaded dynamically. The end goal was to adjust its width to have the combined width of its direct children elements. Once rendered the HTML looked something like this:

<figure><img src="01.jpg" alt="" width="" /></figure>
<figure><img src="02.jpg" alt="" width="" /></figure>
<figure><img src="03.jpg" alt="" width="" /></figure>
// continue…

When looking at the HTML snippet above, notice we are missing the values for the width attribute. This won’t help us, because we won’t be able to calculate the total width combined. This “roadblock” forced me to go back and reconsider the PHP function I wrote to create this image gallery.

STEP 1: PHP getimagesize function

PHP scandir is my favorite function to build an HTML page with images from a selected path. ( I suppose one can do the same with the glob function as well ). Anyway, the trick is not to overlook another less popular function called getimagesize. This function returns an array, ( being width the first array item ). Having this information available, I could now build our HTML by passing the correct value to the width attribute.

   function gallery($dir, $sort) {
      $pattern = '.jpg';      
      $files = scandir($dir, $sort);
      foreach ($files as $key => $file) {     
        if (strpos($file, $pattern)):
        $gallery[] = $file;
      foreach ($gallery as $key => $file) {
        $get_width = getimagesize($dir . $file);
        $width = $get_width[0];
        $output .= '<figure><img src="' . $dir . $file . '" alt="" width="' . $width . '" /></figure>' . "\n";
    return $output;
<?php echo gallery('./gallery/' . $some_variable . '/', 0); ?> // zero: sort ascending

As you can see, I call the getimagesize function on line 13, then we pass the return value to a variable, and allow the foreach iteration to build the HTML for us.

STEP 2: JQUERY width() method

The width() method will return the width of each image inside of our selected element, in this case the <section> element. The each() method iterates over a jQuery object, executing a function for each matched element. We can now calculate the combined width, then assign it to a variable, and lastly call css() method.

<script type="text/javascript">
    $(document).ready(function() {
    var _width = 0;
    $('section figure img').each(function() {            
         _width += $(this).width(); 
         //; // safari debug

    $('section').css({ 'width': _width });

Task complete. — Once the document is ready, jQuery css() method will add or correct the width of the <section> element.

Leave a Reply