Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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;
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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)'>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda