Below is how I would approach the problem. I found reading through your version a bit confusing with regards to the particular mix of variable scope, passed params and jQuery applied params - this might be why you were finding it hard to debug.
- Avoid using closures if you don't need to, they can be complicated, prone to errors, and cause memory leaks if you're not careful.
- When applying src attributes to images I think it is better to apply the load listener before doing so, but this could just be make-believe, it's just something I've always thought would make sense.
- Use the power of jQuery where you can as it makes your life easier :)
- You shouldn't need to use a temporary image to avoid css sizing issues.
- IMG.complete is your friend with regards to image caching problems.
Which lead me to the following:
var resizeImages = function( imgs, img_ratio ){
/// not sure what you're passing to this function but the following
/// should handle an array of images elms or a jQuery collection of images
var images = ( imgs instanceof jQuery ? imgs : $().pushStack(imgs) );
var resizeImage = function( img ){
var cn, st, ow;
/// make it so we can call this function in two ways
if ( !img ) { img = $(this); }
/// store items of the image
cn = img.attr('class');
st = img.attr('style');
/// remove those items so they don't get in the way of original width
img.attr('class','').attr('style','');
/// get the original width
ow = img.width();
/// place back the things we've removed - changes wont render visibly
/// till code execution finishes at the end of this function call.
img.attr('class',cn);
img.attr('style',st);
/// apply the resize
img.css('width', ow * img_ratio );
}
images.each(function(){
var img = $(this);
/// check if the image is already loaded, if so, resize directly
if ( img.get(0).complete ) {
resizeImage(img);
}
/// if the image isn't loaded yet, rely on an image load event
else {
img.load(resizeImage);
};
});
};
Now the less wordy version :)
var resizeImages = function( images, scale ){
var cn, st, ow, resizeImage = function( img ){
img = img || $(this);
cn = img.attr('class');
st = img.attr('style');
ow = img.attr('class','').attr('style','').width();
img.attr('class',cn).attr('style',st).css('width', ow * scale );
}
( images instanceof jQuery ? images : $().pushStack(images) )
.each(function(){
( this.complete ? resizeImage($(this)) : $(this).load(resizeImage) );
});
};
$(function(){
resizeImages( document.images, 0.5 );
});