'Hide img when alternate image not exists

In asp.net img tag I need to set gif image. I set gif image for src of the img and if gif doesn't exist I need to set jpg for the img. But if the jpg also not exists I need to hide the img from the page. I used onerror event of the img tag for this with the javascript function. But at sometimes it saying the function not found.

Is there ay easy way to do this. My need is to set gif to img and if the gif not exists set jpg to it and if jpg also not exists need to hide the img.

I tried like this

<img src="mygif.gif" onerror="setJpg($(this));">

function setJpg(source) {
        var file = source[0].src;
        var jpgFile = file.substr(0, file.lastIndexOf(".")) + ".jpg";

        var img = document.createElement('img');// new Image();
        img.onload = function () { source[0].src = jpgFile; };
        img.onerror = function () { source.parent().hide() };

        img.src = jpgFile;
    }


Solution 1:[1]

The onerror event eventually gets recalled after changing the src of the image. So you do not have to create another img and can resue the same event. Like set a new handler or check for the ending.

//REM: Note that "img" is an element and not jquery wrapped.
function setJpg(img){
  console.log('Called onerror');
  
  //REM: If image ends with ".gif"
  if(img.src.toLowerCase().endsWith('.gif')){
    //REM: Change ".gif" to ".jpg", whatever your logic is.
    //REM: This is going to call onerror again if not found
    img.src = img.src.replace('.gif', '.jpg');
    console.log('Changed src', img.src)
  }
  else{
    //REM: Remove the event
    img.onerror = null;
    //REM: Remove the image or do whatever you want with it
    img.remove();
    console.log('Removed element')
  }
}
<img src = 'wayne.gif' onerror = 'setJpg(this)'>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lain