Quantcast
Channel: Jquery | Matthew Hailwood » Matthew Hailwood
Viewing all articles
Browse latest Browse all 6

Nifty Tricks: Setting a fallback source if an image fails to load.

$
0
0

This useful little snippet allows you to set a backup source for an image if it fails to load. useful in a lot of situations, e.g. listing a directory contents, putting an image next to each item based on it’s extension using this code snippet if you do not have an image for a particular extension it will fall back to your default.

var backup_src = 'http://domain.ext/images/backup.png';
var wanted_src = 'http://domain.ext/images/wanted.png';
var image = $(''); //or point to an image that is already on the page!
image.on('error', function () {
    image.prop('src', backup_src);
});

image.prop('src', wanted_src);

Viewing all articles
Browse latest Browse all 6

Trending Articles