JSFiddle - React, Tailwind, and code Playground
HTML
<div class="image-container"> <a href="javascript:void(0);" class="image-button">
<div class="loading-animation hidden"></div>
<img class="gif-image hidden" src="http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif" gif-data="http://upload.wikimedia.org/wikipedia/commons/d/d3/Newtons_cradle_animation_book_2.gif" />
<img class="jpg-image" src="http://s10.postimg.org/lkz0v3oix/o_e72fd5b6f2cb6041_0.jpg" />
</a>
</div>
CSS
.loading-animation {
background:red;
position:absolute;
width:100px;
height: 100px;
}
.hidden {
display:none;
}
JavaScript
$.loadImage = function (url) {
// Define a "worker" function that should eventually resolve or reject the deferred object.
var loadImage = function (deferred) {
var image = new Image();
// Set up event handlers to know when the image has loaded
// or fails to load due to an error or abort.
image.onload = loaded;
image.onerror = errored; // URL returns 404, etc
image.onabort = errored; // IE may call this if user clicks "Stop"
// Setting the src property begins loading the image.
image.src = url;
function loaded() {
unbindEvents();
// Calling resolve means the image loaded sucessfully and is ready to use.
deferred.resolve(image);
}
function errored() {
unbindEvents();
// Calling reject means we failed to load the image (e.g. 404, server offline, etc).
deferred.reject(image);
}
function unbindEvents() {
// Ensures the event callbacks only get called once.
image.onload = null;
image.onerror = null;
image.onabort = null;
}
};
return $.Deferred(loadImage).promise();
};
$(".image-button").click(function () {
if ($(".jpg-image").is(":visible")) {
$(".loading-animation").show();
var gifImage = $(".gif-image").attr("gif-data");
$.loadImage(gifImage).done(function (image) {
$(".gif-image").attr("src", image.src).show();
$(".jpg-image").hide();
$(".loading-animation").hide();
});
} else {
$(".jpg-image").show();
$(".gif-image").hide();
}
});