replacing 404 image with jQuery(2)

In my previous post, I’ve mentioned a way to load image using ajax but I’ve gotta admit it was pure hack ‘n slash method which wasn’t elegant at all. There’s an excellent jQuery plugin made by Ariel Flesler to handle image preloading nice and easy.

1
2
3
4
5
6
7
8
9
10
11
var $j = jQuery.noConflict();
$j(function(){
    var phImage	= "placeholder.jpg"; //url to placeholder image while image loads.
    var altImage = "nophoto.jpg"; //alternative image to show if image fails loading.
        $j("div.some-class img") //selector
            .preload({
		placeholder:phImage,
		notFound:altImage,
		threshold:1
	    });
});

Since I wanted to make images to fade-in, I’ve added an effect on onComplete handler. Notice I didn’t chain hide() before preload(). In some browsers $(document).ready fires so slow thus hiding at $(document).ready can be too late making image to flicker. So I added the last line to dynamically modify style, rather than hard-coding the css file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var $j = jQuery.noConflict();
$j(function(){
    var phImage	= "placeholder.jpg"; //url to placeholder image while image loads.
    var altImage = "nophoto.jpg"; //alternative image to show if image fails loading.
        $j("div.some-class img") //selector
            .preload({
                onComplete:function(data){
		    $j(data.original).fadeIn();  // this will make image to fadein after loading.
		},
		placeholder:phImage,
		notFound:altImage,
		threshold:1
	    });
});
$j('head').append('<style>div.some-class img{display:none;}</style>');

One Comment

  1. Ruby Jones says:

    Flicker is really great when sharing photos over friends and families. I love the resize feature of Flickr.-,:

Leave a Reply