var images = [{'url': 'http://lorempixel.com/320/320', 'isCached': false },
{'url': 'http://lorempixel.com/321/321', 'isCached': false },
{'url': 'http://lorempixel.com/322/322', 'isCached': false },
{'url': 'http://lorempixel.com/323/323', 'isCached': false }
],
idx = 0, len = images.length;
displayImage(0); // intitially display first image on page load right away
$("#nxt").on("click", function() {
idx = (++idx % len); displayImage(idx);
});
$("#prv").on("click", function() {
idx = (idx + len - 1) % len; displayImage(idx);
});
$("img").on("load", function() { showImage($(this)); }); // handle load event on image
function displayImage(idx) {
var $currentImage = $("#d" + (idx + 1)).find("img");
$currentImage.attr('src', images[idx].url); // set the src from current array index
if (images[idx].isCached) { showImage($currentImage); } // if cached, show
else { images[idx].isCached = true; } // if not cached, let load handler work
}
function showImage($img) {
$("img").removeClass("show"); $img.addClass("show"); // your routine here
}
div { float: left; }
img {
width: 0; opacity: 0;
transition: width 100ms, opacity 1s 250ms;
}
img.show { width: auto; opacity: 1; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="prv">< Previous</button><button id="nxt">Next ></button>
<hr />
<div id="d1"><img /></div>
<div id="d2"><img /></div>
<div id="d3"><img /></div>
<div id="d4"><img /></div>