I want to set manual dummy image if particular image is not available on website. Also how to set if that image is deleted on server or not available, in that case also i need to display default image using JS.
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
We can use the onerror attribute on the image to set a fallback. We use the onerror to set the error to null and set the src of the image to a fallback. In our case, a photo of a missing cat. Note: It's not a great practice to rely on external images.
This is cross-browser, vanilla JavaScript
and comes along without any ugly onerror=""
markup:
var sPathToDefaultImg = 'http://lorempixel.com/150/100/abstract/2/Placeholder/';
var replaceImageWithPlaceholderIfNotAvail = function( domImg ) {
// sanitize domImg
if ( !domImg || !domImg.nodeName || domImg.nodeName != 'IMG' ) {
// get all images from DOM
aImg = document.getElementsByTagName('IMG');
i = aImg.length;
if ( i ) {
while ( i-- ) {
replaceImageWithPlaceholderIfNotAvail( aImg[i] );
}
}
return;
}
// here is where the magic happens
oImg = new Image(); // create new Image
oImg.onerror = function() { // assign onerror
domImg.src = sPathToDefaultImg; // handler function
};
oImg.src = domImg.src; // set src of new Image
};
// now you can use the function on "auto pilot"
replaceImageWithPlaceholderIfNotAvail()
// or feed with any domImage you like to evaluate
// replaceImageWithPlaceholderIfNotAvail( domCustomImg )
Available: <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png" alt="notavail1.jpg"><br>
Not Available: <img src="notavail1.jpg" alt="notavail2.jpg"><br>
Available: <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png" alt="notavail1.jpg"><br>
Not Available: <img src="notavail2.jpg" alt="notavail4.jpg">
CODEPEN:
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