A lazy loader doesn't feel elegant at all unless it is given some sub features like a loading icon. This notion was dealt with in the previous Loading Icons chapter where we gave different types of icons to our .lazy container uptil the the point the underlying image loaded.

But is an icon the only thing that can make our loader look nice? Is there anything else we can do in addition? That anything is to give a fade-in effect to our image as it loads into view.

Building the fade effect

The idea is that instead of showing the image instantly as it loads we transitionally fade it in. Giving a fade-in effect in CSS is extremely simple - just the matter of three properties: opacity, visibility and transition.

To get the effect work properly we will start by constructing a class .unloaded to be given to the lazy image .lazy-img. This class will serve to hold the initial state of our transition; where the final state will be given by removing this class.

The class will hold opacity: 0 and visibility: hidden to hide the image.

.lazy .unloaded {
    opacity: 0;
    visibility: hidden;

And now let's give .lazy-img a transition to smoothly transition between its initial and final states.

.lazy-img {
    transition: 0.5s linear;
If you've worked with CSS and JavaScript class toggles and then transitions, you'll agree that there isn't anything complicated or new in this.

For the JavaScript, we first need to add the class .unloaded to the lazy image and once it loads then remove it. We can also add this class to .lazy-img manually in the HTML, but it's convenient to add it in the JavaScript.

lazyImage.classList.add("unloaded"); // add class .unloaded
lazyImage.onload = function() { = "none";
    lazyImage.classList.remove("unloaded"); // remove class .unloaded
Depending on the way you gave a loading icon to your lazy loader, you would need to include = "none" in the load event of lazyImage as illustrated above in line 3. Without it the icon will not disappear, and remain animating.

This marks the completion of the fade effect - check it out below and see the added elegance to our lazy loader!

Fade Effect Loader