babbaggeii
babbaggeii

Reputation: 7737

Find out if image exists at url with wildcard

I'm trying to display an image, but revert to a default image if it doesn't exist. But the image can have any image extension. So how can I add a wildcard to the $.get() function below to make it look for any file with the right filename?

$.get('path/to/file.*')
    .done(function() {

    }).fail(function() {

    });

Upvotes: 1

Views: 653

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

A solution that will try a list of extensions and if none works will apply the default image is

var validImageExtensions = ['jpg','png','gif'];

function imageOrDefault( path, defaultPath, target, index ){
    var img = $('<img>'),
        extensionIndex = index || 0;

    $(img)
        .on('load', function(){
            target.prop('src', img.prop('src'));
        })
        .on('error', function(){
            if (extensionIndex === validImageExtensions.length){
                target.prop('src', defaultPath);
            } else {
                imageOrDefault( path, defaultPath, target, extensionIndex +1);
            }
        });
    img.prop('src', path + '.' + validImageExtensions[extensionIndex]);
}

Usage

imageOrDefault('path/to/image/without-extension', 'path/to/default.png', $('.target-selector'));

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

The img element raises an error event when the src fails. As such you can use the following jQuery without the need for AJAX requests (which would mean nImages+1 requests being made):

$('img').on('error', function() {
    $(this).prop('src', '/path-to/default-image.png');
});

Upvotes: 1

Related Questions