Reputation: 55
How would I program a loading icon or graphic that appears while images on a page load. An example would be http://landerapp.com/?
My goal is to prevent the user from seeing this images on screen until they are ready to animate (see the problem at http://tsawebmaster1.hhstsa.com/index.html).
Upvotes: 1
Views: 3598
Reputation: 630
If you are using Vanilla
or jQuery
I'd suggest you to use imagesLoaded which is meant to achieve exactly what you want.
I'd go with something like this:
$(function(){
$('.img-container img').imagesLoaded().done(function(){
console.log('images loaded');
$('.img-container .loader').remove();
$('.img-container img.hide').removeClass('hide');
}).fail(function(){
console.log('FAILED TO LOAD IMAGES');
});
});
.img-responsive {
max-width : 100%;
}
.hide {
display : none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.2.0/imagesloaded.pkgd.min.js"></script>
<div class="img-container">
<div class="loader">
Loading image....
</div>
<img src="http://mascotafiel.com/wp-content/uploads/2015/10/perros-Husky-Siberiano_opt-compressor-1.jpg" alt="PrettyCoolImage" class="img-responsive hide">
</div>
Upvotes: 0
Reputation: 19119
Let's begin with a visible loading image that is fixed in the exact middle of the screen. Then, when the page is fully loaded, we'll add a "page_loaded"
class on the <body>
which:
[1] begins the fade out of the loading image
[2] begins the fade in and translation of offscreen images to the screen
window.onload = function() {
document.body.classList.add("page_loaded");
}
.loader {
opacity: 1;
transition: 2s opacity;
height: 300px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.right,
.left {
height: 100px;
position: absolute;
transition: 1s 2s;
opacity: 0;
}
.left {
left: 0;
transform: translateX(-50em);
}
.right {
right: 0;
transform: translateX(50em);
}
.page_loaded .loader {
opacity: 0;
}
.page_loaded .right,
.page_loaded .left {
opacity: 1;
transform: translateX(0);
}
<img class="loader" src="https://d13yacurqjgara.cloudfront.net/users/82092/screenshots/1073359/spinner.gif" alt="" />
<img src="https://www.petfinder.com/wp-content/uploads/2012/11/140272627-grooming-needs-senior-cat-632x475.jpg" alt="" class="right" />
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTS704tVMgbKCry10AhT09VE8wBY5S9v-PWxTBOa7o52JU0TsjH" alt="" class="left" />
Upvotes: 2