5

Possible Duplicate:
jQuery callback on image load (even when the image is cached)

Is there a way to check if image is loaded by jquery? I have some images with external src and sometime src points to 404 page. Is there a way to check if that image is loaded? and then I can remove it from dom otherwise.

Thanks.

Community
  • 1
  • 1
user558134
  • 1,071
  • 6
  • 25
  • 38

3 Answers3

6

jQuery has a function to deal with this, take a look at .error()

So for example you could attach an .error() handler to all images and display something else if there is an error, like the source no longer exists:

$('img').error(function() {
    $(this).hide();
}).attr("src", "missing.jpg");

Here is a demo

Scoobler
  • 9,696
  • 4
  • 36
  • 51
  • 1
    You've got it backwards - don't hide the image, and you should set the `src` in the callback. See my answer. – Matt Ball Jun 09 '11 at 15:37
6

@Scoobler has the right idea, but the wrong implementation.

$(function ()
{
    $('img').error(function()
    {
        $(this).attr('src', 'https://i.stack.imgur.com/THJzu.gif');
    });
});

The .error() binding must take place on document ready - window load is too late.

Demo: http://jsfiddle.net/mattball/EebmC/

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

yes you can use error event like this....

$('#imageId')
  .error(function() {
    alert('Something bad happened.')
  })
  .attr("src", "image.gif");
Vivek
  • 10,978
  • 14
  • 48
  • 66
  • 1
    @ Vivek.... ;) Instead of 'use' use ...'test'. Or we'll suppose you use *alerts* all around your web pages! ;) This looks like a modifyed copy-paste answer of the previous answer. – Roko C. Buljan May 20 '11 at 09:29