How to load default image if src="" does not find?

Asked

Viewed 4,778 times

11

Is there any way to upload a standard image, using only HTML, case the first src="" can’t find the file?

<img src="ola_mundo.png" alt="Olá Mundo"> // Existe algum atributo para isso?

2 answers

7


Other fallbacks simpler than you can try, with javascript:

<img src="imagem-nao-existe.png" onerror="this.src='fallback.png'">

An example in @Randrade jsfiddle: https://jsfiddle.net/wts9e4xb/1/

Sem error
<br>

<img src="http://previews.123rf.com/images/otnaydur/otnaydur1103/otnaydur110300040/9112843-Gold-coins-stack-over-scater-coins-Stock-Photo-bar.jpg" alt="Olá Mundo" onerror="this.onerror=null;this.src='http://logz.io/wp-content/uploads/2016/02/stack-overflow-logo.png';"
>

<br>Com error
<br>

<img src="loading.gif" alt="Olá Mundo" onerror="this.src='http://logz.io/wp-content/uploads/2016/02/stack-overflow-logo.png';" >

With CSS (requires fixed size):

<style>
.image {
     width: 620px;
     height: 480x;
}
</style>

<div class="image" style="background: url(foto-nao-existe.png), url(fallback.png)"></div>
  • 1

    Well, even using JS I believe it is still the best solution.

6

I found this solution...

<object data="https://img.com.br/no_existe.jpg" type="image/png">
  <img src="http://farm2.static.flickr.com/1094/984405951_34580c3cb9.jpg" />
</object>

In that question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.