Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda