How can I make this jQuery plugin chainable after all image load events have completed?
Posted
by
BumbleB2na
on Stack Overflow
See other posts from Stack Overflow
or by BumbleB2na
Published on 2011-11-25T20:22:57Z
Indexed on
2012/12/11
17:04 UTC
Read the original article
Hit count: 170
jQuery
|jquery-plugins
[UPDATE] Solution I decided on:
Decided that passing in a callback to the plugin will take care of firing an event once all images have completed loading. Chaining is also still possible. Updated Fiddle
I am building a chainable jQuery plugin that can load images dynamically.
(View the following code as a JSFiddle)
Html:
<img data-img-src="http://www.lubasf.com/blog/wp-content/uploads/2009/03/gnome.jpg" style="display: none" />
<img data-img-src="http://buffered.io/uploads/2008/10/gnome.jpg" style="display: none" />
Instead of adding in a src
attribute, I give these images a data-img-src
attribute. My plugin uses the value of that to fill the src
. Also, these images are hidden to begin with.
jQuery plugin:
(function(jQuery) {
jQuery.fn.loadImages = function() {
var numToLoad = jQuery(this).length;
var numLoaded = 0;
jQuery(this).each(function() {
if(jQuery(this).attr('src') == undefined) {
return jQuery(this).load(function() {
numLoaded++;
if(numToLoad == numLoaded)
return this; // attempt at making this plugin
// chainable, after all .load()
// events have completed.
}).attr('src', jQuery(this).attr('data-img-src'));
} else {
numLoaded++;
if(numToLoad == numLoaded)
return this; // attempt at making this plugin
// chainable, after all .load()
// events have completed.
}
});
// this works if uncommented, but returns before all .load() events have completed
//return this;
};
})(jQuery);
// I want to chain a .fadeIn() after all images have completed loading
$('img[data-img-src]').loadImages().fadeIn();
Is there a way to make this plugin chainable, and have my fadeIn()
happen after all images have loaded?
© Stack Overflow or respective owner