Search code examples
jqueryimagetypeerroronerror

jQuery to perform an event when an image is broken


I found this problem mentioned before here jQuery/Javascript to replace broken images

and this was the best answer.. I tried it and it's working fine

function ImgError(source){
   source.src = "/images/noimage.gif";
   source.onerror = "";
   return true;
}

<img src="someimage.png" onerror="ImgError(this);"/>

but when I tried to preform other events in the previous function

function ImgError(source){
   source.hide(); // hide instead of replacing the image
   source.onerror = "";
   return true;
}

I got this error

TypeError: 'undefined' is not a function (evaluating 'source.hide()')

Every single jQuery event/method I tried that function I got a TypeError.

What's the problem?


Solution

  • Because .hide() is a jQuery element.

    Try that:

    function ImgError(source) {
       $(source).hide();
       source.onerror = "";
       return true;
    }