Search code examples
jqueryimagecropresize-crop

Crop image to correct size by tweaking the image url


I am trying to crop Lazyload image to correct size. So i have simple jquery plugin given below that can resize and crop the image to correct size by tweaking the image url. This jQuery code automatically crop the image to the correct size. But when i use Lazyload plugin for load image the script not able to crop image.

JS:

var w = 200;
var h = 150;
$('#crop').find('img').each(function(n, image){
  var image = $(image);
  image.attr({src : image.attr('src').replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c')});
  image.attr('width',w);
  image.attr('height',h);
 });

HTML: Fiddle: http://jsfiddle.net/kh5btqyu/3/ (with out Lazyload)

<div id="crop">
<img src=""/>
</div>

Lazyload HTML: Fiddle: http://jsfiddle.net/v2fud3a4/4/ (unable to crop)

<div id="crop">
<img data-src=""/>
</div>

Actually Lazyload plugin works when we change image src <img src=""/> to data-src <img data-src=""/> and when we scroll down page, when image get window viewport then it replace image link <img data-src=""/> to <img data-src="" src=""/> then images will visible.

So my image crop plugin not able to find image scr link. Because for Lazyload plugin we have <img data-src="" src=""/> link. Another reason is my image crop plugin run after page load, but Lazyload make loads image on window viewport, when we scroll down page and image get window view.

My question is there are any way to run my image crop plugin, when lazyload plugin replace image link <img data-src=""/> to <img data-src="" src=""/>, means my crop plugin run when Lazyload plugin has loaded image.

Thanks.


Solution

  • The trick is to call your re-sizing function after lazy loading of image.

    $.extend($.lazyLoadXT, {
        onload:myfunc
    });
    
    
    function myfunc(){
        var w = 200;
    var h = 150;
    $('#crop').find('img').each(function(n, image){
      var image = $(image);
      image.attr({src : image.attr('src').replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c')});
      image.attr('width',w);
      image.attr('height',h);
     });
    }
    

    here is fiddle