Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fallback img src for images from external sites

I need to display images from other sites and have a view model with a imgsrc property that references an image URL. Then I have the following HTML binding:

<img data-bind="attr: { src : imgsrc }" />

The problem is that with a bound image being external, I could get a 404 or 500 response if the external site is having issues; therefore, I want to display a fallback image in case we can't load the image.

How can this be achieved using KnockoutJS?

like image 707
Mike Avatar asked Oct 04 '22 00:10

Mike


1 Answers

You can use the onerror event.

HTML:

<img id="pic" data-bind="attr: { src : imgsrc }" />

JavaScript:

var myViewModel = {
    imgsrc: ko.computed(function () {
        var pic = document.getElementById('pic');
        pic.onerror = function () {
            pic.src = 'fallback image url';
        };
        return 'image url';
    }, this)
};

ko.applyBindings(myViewModel);

Example: http://jsfiddle.net/R4SV7/1/

like image 149
gkatai Avatar answered Oct 12 '22 11:10

gkatai