How to fade images on load with jQuery

In this article, I will show you how to properly fade in images when the page loads using jQuery.

Although this has been covered by other blogs, most proposed solutions do not take caching into account. When returning on a page, images that were cached by the browser will not trigger jQuery’s load event.

First, we bind the animation to the load of all images. Once this is done, we loop through the images using each, and manually trigger the load event for images that are already loaded because of caching.

$('img').hide().one("load",function(){
    $(this).fadeIn(500);
}).each(function(){
    if(this.complete) $(this).trigger("load");
});

In this example, we apply the effect to all images, which might impact performance. Replace the selector at the beginning of the snippet to limit it to the images you want to fade in.

If you want to see this jQuery snippet in effect, visit my personal website. If you want to learn jQuery properly, I highly recommend Mark Myers’ “A Smarter Way to Learn jQuery“. Mark Myers tends to write very high quality programming books with a focus on good practices.

2 comments on “How to fade images on load with jQuery

  1. Hi, is this code valid

    $(‘img’).hide().one(“load”,function(){
    $(this).fadeIn(500); }).each(function(){
    if(this.complete) $(this).trigger(“load”); });

    I never seen .one("load") function!

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax