Reputation: 466
I am using this code to show loader effect while image load:
$(function(){
jQuery('figure').append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
jQuery('.img').load(function(){
jQuery('.loader').remove();
});
});
But I want this code in a function so that I can call it on any image. JSFIDDLE
Upvotes: 0
Views: 76
Reputation: 43156
What you are passing to $()
is already a function which is anonymous.
If you want to call it somewhere else you can simply give it a name like
function showSoader(){
jQuery('figure').append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
jQuery('.img').load(function(){
jQuery('.loader').remove();
});
}
You can bind it to ready like $(showSoader)
and call it anywhere else like showSoader()
.
If you want to generalize it to work with multiple elements, simply specify a parameter to access the element:
function showSoader(selector){
var $elm = $(selector);
$elm.append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
$elm.find('.img').load(function(){
$elm.find('.loader').remove();
});
}
Which you call call like showSoader("#myImgContainer")
worth noticing:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
- It doesn't work consistently nor reliably cross-browser
- It doesn't fire correctly in WebKit if the image src is set to the same src as before
- It doesn't correctly bubble up the DOM tree
- Can cease to fire for images that already live in the browser's cache
Upvotes: 2
Reputation: 1335
JQuery
jQuery.fn.extend({
loadImage: function() {
return this.each(function() {
var loading= jQuery('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>').insertBefore(jQuery(this));
jQuery(this).load(function(){
loading.remove();
}).error(function() {
loading.remove();
});
});
}
});
$(".img").loadImage();
Upvotes: 0