13

Basically what the title says.

I'm making an html page, and using images for link. But can I make it so the images show a default icon if the specified file hasn't been found?

StevoHN
  • 400
  • 1
  • 5
  • 18

6 Answers6

43

You'll have to use javascript:

<img src="404image" onerror="this.src='images/not_found.png';" />
x13
  • 2,093
  • 1
  • 9
  • 27
  • 1
    In addition a resource for none inline handlers http://stackoverflow.com/questions/12512539/javascript-onload-and-onerror-called-together – Asons Oct 02 '15 at 14:37
20

If you specify the width and height of an image in the css, you can set the background image as a not-found image:

img {
  width:100px;
  height:100px;
  background: url(http://goo.gl/vyAs27) no-repeat scroll 0 0;
}
<img src="not-found.png" /><img src="http://goo.gl/ijai22" />

Most browsers will insert an image missing icon in the corner. There's no way that I know of to remove this.

As you can see, your regular image will overlay the background image.

If your image has a transparent background then the background image will be visible behind the loaded image.

Alternatively, use a server-side programming language that checks if the image exists. If it does not, load a placeholder...

Richard Parnaby-King
  • 14,376
  • 11
  • 66
  • 125
1

If you just want to display a blank space without any dummy image/caption, remove the alt option that you have specified in the img tag.

<img src='not_found.jpg' alt='' class=''>

Here the source not_found.jpg is the wrong path which won't give any image. PFA for sample o/p.

  • Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.

Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.

Swaps
  • 1,350
  • 20
  • 30
0

img {
  width:100px;
  height:100px;
  background: url(https://i0.wp.com/reviveyouthandfamily.org/wp-content/uploads/2016/11/house-placeholder.jpg?ssl=1) no-repeat scroll 0 0;
}
<img src="not-found.png" /><img src="https://i0.wp.com/reviveyouthandfamily.org/wp-content/uploads/2016/11/house-placeholder.jpg?ssl=1" />
-2

Set images resolution what you need. for example, I need image size: 100X100. put live of image path or set proper path of an image source for your folder.

CSS:

img {
   width:100px;
   height:100px;
}

HTML:

<img src="https://dummyimage.com/100/00ff48/ff0000.png&text=Image+Found" alt="not found image" />
HAPPY SINGH
  • 512
  • 4
  • 12
  • The question was how to handle a case where an image fails to load. This is just an example of a standard image element with a static source. While the CSS styling addresses some drawbacks of other answers, it doesn't at all answer the question being asked. – Air Jul 30 '20 at 19:00
-7

p {
  font-family: "Lucida Console", "Courier New", monospace;
  }
    <!DOCTYPE html>
    <html>
      <body>
        <p>hi</p>
      </body>
    </html>
345
  • 1