Dmytro
Dmytro

Reputation: 17176

How to show default image if image isn't loaded properly?

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?

Upvotes: 1

Views: 863

Answers (2)

Roamer-1888
Roamer-1888

Reputation: 19288

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

Upvotes: 2

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can use .load() for this problem:

$(this).load(defaultSrc);

Upvotes: 0

Related Questions