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
  • 951
  • 5
  • 21
  • 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,538
  • 4
  • 34
  • 51
6

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

$(function ()
{
    $('img').error(function()
    {
        $(this).attr('src', 'http://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
  • 332,322
  • 92
  • 617
  • 683
0

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

$('#imageId')
  .error(function() {
    alert('Something bad happened.')
  })
  .attr("src", "image.gif");
Vivek
  • 10,426
  • 14
  • 44
  • 65
  • 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