Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set manual default image, if image is not available on my site using js?

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.

like image 830
gopigoppu Avatar asked Aug 19 '14 05:08

gopigoppu


People also ask

How do you show an alternate image if source image is not found?

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.

How do I create a fallback image in HTML?

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.


1 Answers

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:

like image 123
Axel Avatar answered Sep 28 '22 08:09

Axel