Skip to content

Instantly share code, notes, and snippets.

@cyberdev
Created April 11, 2021 03:55
Show Gist options
  • Save cyberdev/e19a41c0bb60e9e208d6c7c987c8880a to your computer and use it in GitHub Desktop.
Save cyberdev/e19a41c0bb60e9e208d6c7c987c8880a to your computer and use it in GitHub Desktop.
Load image using filename no extension
var validImageExtensions = ['jpg','png','gif','jpeg'];
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 - 1){
target.prop('src', defaultPath);
} else {
imageOrDefault( path, defaultPath, target, extensionIndex +1);
}
});
img.prop('src', path + '.' + validImageExtensions[extensionIndex]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment