Skip to content

Instantly share code, notes, and snippets.

@tmoitie
Last active December 21, 2015 19:19
Show Gist options
  • Save tmoitie/6353159 to your computer and use it in GitHub Desktop.
Save tmoitie/6353159 to your computer and use it in GitHub Desktop.
(function($) {
/*
* Replace image source by fading out, preloading and fading in
* usage: $('img').replaceImageSrc('http://example.com/kitten.jpg');
*/
$.fn.replaceImageSrc = function(newUrl, options) {
var settings = $.extend({
duration: 'slow'
}, options);
var imgPreload = new Image();
imgPreload.src = newUrl;
return this.each(function() {
var $imgArea = $(this);
$imgArea.fadeOut({
duration: settings.duration,
complete: function() {
var finishLoad = function() {
$imgArea.attr('src', newUrl);
$imgArea.fadeIn(settings.duration);
};
if (!imgPreload.complete && !imgPreload.readyState === 4) {
$(imgPreload).one('load', function(){
finishLoad();
});
} else {
finishLoad();
}
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment