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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With