In this example, I am showing how to display image when its completely received by browser. We need this kind of thing when we are changing any Image through JavaScript and want to show some loader until image is not completely receive by client browser. I am using Image onload event for this purpose. Its fires when image is load by browser. When user click on prev or next link we hide the image by adding the ‘hide‘ class to ‘<img>‘. So, user will see the loader image which we placed in the background of image container. When browser load the next image we removed the ‘hide‘ class from ‘<img>‘ and changed its ‘src‘ from older image to new image. I am also using jQuery for adding and removing CSS class from HTML Element. Check out the Javascript, CSS and HTML code below.
HTML Code:-
<div class="container"> <div class="prev"><a id="prev" href="javascript:void(0);">«Prev</a></div> <div class="image-container"><img id="pic" src="img/blank.jpg" class="hide" /></div> <div class="next"><a id="next" href="javascript:void(0);">Next»</a></div> <div class="clear-float"></div> </div>
CSS Code:-
<style type="text/css" media="screen"> * { margin:0; padding:0; border:0; font-family:Arial, Helvetica, sans-serif; font-size:1em; font-weight:normal; font-style:normal; text-decoration:none; color:#666; } .container { width:800px; margin-left:auto; margin-right:auto; } .image-container { height:300px; width:400px; border:#333333 thin dashed; margin-top:100px; background:url(img/indicator2.gif) center no-repeat; float:left; } .image-container img { height:300px; width:400px; } .prev{ width:50px; float:left; margin-left:143px; margin-top:250px; } .next{ width:50px; float:left; margin-top:250px; text-align:right; } .clear-float { clear:both; height:1px;} .hide { display:none;} </style>
JavaScript Code:-
<script type="text/javascript" src="img/jquery.js"></script> <script language="javascript"> $(document).ready(function() { var index = 0; var path = 'img/'; var images = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg"]; var pre_images = new Array(); var loaded = new Array(); $("#prev").click(function() { index--; $("#pic").addClass('hide'); if (index < 0) {index = images.length - 1} getImage(); }); $("#next").click(function() { index++; $("#pic").addClass('hide'); if (index >= images.length) {index = 0} getImage(); }); function getImage() { if (loaded[index] == true) { document.getElementById("pic").src = pre_images[index].src; $("#pic").removeClass('hide'); } else { pre_images[index] = new Image(); pre_images[index].src = path + images[index]; pre_images[index].onload = function() { loaded[index] = true; document.getElementById("pic").src = pre_images[index].src; $("#pic").removeClass('hide'); } } } getImage(); }); </script>
