Reputation: 1194
I am trying to crop Lazyload image to correct size. 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 after Lazyload plugin load images. But it's not able to crop all images, it crop only one from all images.
Fiddle: http://jsfiddle.net/e0myc0po/4/
See that it has cropped only image no 3 !
JS:
External Resources: https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyloadxt/1.0.5/jquery.lazyloadxt.js
$.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);
});
}
function myfunc(){
var w = 200;
var h = 150;
$('#another-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:
1
<div id="crop">
<img data-src=""/>
</div>
<br/>
2
<div id="crop">
<img data-src=""/>
</div>
<br/>
3
<div id="another-crop">
<img data-src=""/>
</div>
<br/>
4
<div id="another-crop">
<img data-src=""/>
</div>
So my question is why it's not crop all images and what is the solution is?
Thanks.
Upvotes: 0
Views: 862
Reputation: 2741
There is no need to define same function twice. Check this fiddle http://jsfiddle.net/3xphkmsq/ you just have to mention a class
instead of id
Upvotes: 1
Reputation: 1836
Easy. You've got two or more ID's of an HTML tag and two declaration of function myfunc(). The ID of any tag element on a single page should be unique!! :)
<div id="crop">
....
<div id="crop-foo">
....
<div id="crop-something-else">
Change id="crop" to class="crop" and then in JS #crop to .crop Same goes with: #another-crop / id="another-crop" - change it to a class
Also make one 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);
});
$('#another-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);
});
}
Working example: http://jsfiddle.net/e0myc0po/6/
Upvotes: 2