1

I've came up with this solution (jsfiddle) - implement $.error function and change image src attribute, but seams that this function is not always called and sometimes I get this default image image with alt text instead of one I provided. I use this jquery code to update images:

$(document).ready(function() {
    $('img').error(function () {
        var defaultSrc = $(this).data('default-src');
        $(this).attr('src', defaultSrc);
    });
});

data-default-src attribute is also provided for each image. Is there some more advanced and certain jquery solution?

Dmytro
  • 16,668
  • 27
  • 80
  • 130
  • This might help you http://stackoverflow.com/a/93017/3639582. – Shaunak D Apr 06 '15 at 05:07
  • @ShaunakD, it's better, but now default image is displayed way to often, original image is displayed after page refresh though... – Dmytro Apr 06 '15 at 05:30
  • @RohitArora `img` selector means select all `img` elements on page – Dmytro Apr 06 '15 at 05:31
  • @ShaunakD, no, my bad, I used `$(document).ready()` instead of `$(window).load()`, now it works almost perfect. If you post the answer i'll accept it. – Dmytro Apr 06 '15 at 05:43
  • You used `$(window).load()`. I had referred the existing answer which wasn't mine. So I think you should self-answer and accept. – Shaunak D Apr 06 '15 at 05:45

2 Answers2

2

I think you will find that even the $(document).ready event can be too late to attach the .error handler to the imgs. The error event(s) may already have happened before the handler is attached.

As a workaround, you can ensure that the image's src is not set until after the .error handler is in place, for example, like this :

HTML

<img id="1" data-src="/bad/path/to/image" data-default-src="good/path/to/image" />

Javascript

$(document).ready(function() {
    $('img').on('error', function () {
        this.src = $(this).data('default-src');
    }).each(function() {
        this.src = $(this).data('src');
    });
});

Demo

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
0

You can use .load() for this problem:

$(this).load(defaultSrc);
Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34