Search code examples
javascriptjqueryimagedimension

If else statement to pass image size on to surrounding div


On my site all images within the main content are wrapped into a div container like this:

<div class="imagecontainer">
  <img src="image.jpg" width="300" />
</div>

I need to add the images width to its surrounding div. This works using:

$('.imagecontainer').each(function() {
  $(this).width( $(this).find('img').attr('width') );
});

BUT only, if the image has a width attribute. If I use the width() element instead of attr('width') than all images without a width attribute display a width of 0.

I also tried a couple of if-else statement to check:

  1. If the image has a width attribute than add this to its surrounding div.
  2. Else use the images displayed width and add this to its surrounding div.

But without success.

Isnt there a way to grab the images displayed size and add it to its surrounding div?


Solution

  • Using .width() is the right way to do it, but you have to wait for the window to load, so that when you run the code the images have already been loaded:

    $(window).on('load', function () {
        $('.imagecontainer').each(function() {
            $(this).width( $(this).find('img').width() );
        });
    });
    

    You should probably cache that $(this) object.