Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!