1

I have an image wrapper div to contain image and caption.

Using the following the image wrapper div is sized to be the width of the image:

$('.imgright').each(function(){
    $(this).width($(this).find('img').outerWidth());
});

I also wish to use a different image path if dependent on a parent div class. The following works:

$('.grid_12').each(function(){
    $(this).find('img').each(function(){
        $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    });
});

But putting these together does not always set the width of the image wrapper div.

$('.grid_12').each(function(){
    $(this).find('img').each(function(){
        $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    });
});
$('.imgright').each(function(){
    $(this).width($(this).find('img').outerWidth());
});

Any suggestions?

Thanks to 2 very quick answers I have restructured my code and used the .load() function to get the changed image details.

Working code is:

$('.grid_12').each(function(){
   $(this).find('img').each(function(){
     $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
     $(this).load(function(args){
       var newWidth = $(this).outerWidth();
       $(this).parent('.imgright').each(function(){
         $(this).width(newWidth);
       })
     })
   })
});
Milad Rashidi
  • 1,296
  • 4
  • 22
  • 40
chrisk
  • 342
  • 2
  • 3
  • 10

2 Answers2

0

Could it be that the images have not loaded yet? You could add a load handler to the image as you change the ImagePath

$('.grid_12').each(function(){
  $(this).find('img').each(function(){
    $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    $(this).load(function(args){/* find the parent div and change size */});
  });
});
David Waters
  • 11,979
  • 7
  • 41
  • 76
  • Thank you for your very quick reply. Yes, i had guessed that the changed image had not loaded but did not know what I could do. I have amended my code to use your suggestion of .load(function(args) – chrisk Apr 20 '11 at 15:22
0

For starters, you can leverage chaining to make your code a bit more succinct:

$('.grid_12').each(function(){
    $(this)
        .find('img')
            .each(function(){
                $(this)
                      .attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
            })
            .end()
        .width($(this).find('img').outerWidth());
});

Now, as to your problem, what's happening is that you are loading an image (by changing it's src) and then immediately trying to get its dimensions without first checking to see if the image had finished loading yet.

It looks like this question may help steer you in the right direction:

How can I determine if an image has loaded, using Javascript/jQuery?

Community
  • 1
  • 1
DA.
  • 39,848
  • 49
  • 150
  • 213