Auto-resize images with jQuery to fit container

Auto-resize images with jQuery to fit container

by kibria

HTML

<div id='cng' style='width:200px;'>
    <img alt='' src='http://1.bp.blogspot.com/-SZgenQisfQc/TVPnClZOn5I/AAAAAAAABO8/zLFsX4UoFzg/s1600/The-best-top-desktop-dolphin-wallpapers-hd-dolphins-wallpaper-3.jpg'/>
</div>

JavaScript

$('img').one('load', function () {
       
    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    } 
    
});

$('img').each(function () {
     //If image is cached by browsers, trigger .load()
    if (this.complete){        
         $(this).trigger('load');
    }
 });