I’m working with a jQuery plug-in useful to zoom the resized background images with the mouse interaction.
To make it work, I thought to use an array of objects with the width and height of a background-image of every element I bring to it.
To do this I’ve created an empty img element, set the src attribute to the background image, and once it’s loaded getting width and height.
I’ve thought to handle it starting in a for loop which prepares every image, when the jQuery event load is called I create the new array element with every info about the loaded image.
It seems the load event sets the first loaded image, and apply the same properties to every element loaded after it, how can I avoid this problem?
// this is a portion of the plugin
var setImageSize = function (i) {
return function (e) {
// I use the extend method only to get different zoom animation if they are added by the user
instances[i] = {id:i, element:this_obj.get(i), settings:$.extend(true, defaults, options)};
instances[i].settings.bg.url = getBackgroundUrl(i);
instances[i].settings.bg.width = parseInt($(this).width());
instances[i].settings.bg.height = parseInt($(this).height());
updateDefaultValues(instances[i]);
$(instances[i].element).hover(setRollOver(i), setRollOut(i));
$(window).resize(getUpdateDefaultValues(i));
$('#debug').html($('#debug').html() + 'image loaded: ' + i + ' url:' + instances[i].settings.bg.url +'<br/>width: '+ instances[i].settings.bg.width +' height: '+ instances[i].settings.bg.height +'<br>- - - - - <br>');
$(this).remove();
}
}
var prepareImageSize = function (i) {
var img = $('<img id="jquery-background-zoom-'+i+'"/>');
img.hide();
img.bind('load', setImageSize(i));
$('body').append(img);
img.attr('src', getBackgroundUrl(i));
}
var init = function () {
for (var i = 0; i < this_obj.length; i ++) {
prepareImageSize (i);
}
}
init();
I’ve reported a full working example here at http://jsfiddle.net/tonino/CFPTa/
In the plug-in I’ve added a script to see how the images are set, then if you try to interact with the images you’ll notice the props of every images are overwritten by the last loaded image, I’m not sure how?
It seems like the load event overwrite previous load event or something, how can I fix it?
One thing I notice is you pass options into the init function, but never use them…
I think
isn’t doing what you want. That says take options and add it to defaults. You actually want
or if you want your code to be less legible you could do it the way they suggest in the jQuery API docs