Display an image when another image is not loaded

Asked

Viewed 63 times

0

Hello, I’m making a web page on which images are taken from outside the server, but sometimes the image no longer exists, or the link broke, so I’d like to display another image. The code would be like this:


    @if(condição de imagem existe){
    <img src="@imgUrl"/>

    }else{//aqui é quando a imagem não for encontrada, se isso ocorrer eu quero que carregue uma imagem do meu servidor

    <img src="/img.jpg"/>

    }
  • I think this can help you https://answall.com/questions/321138/howto make a styling-break imagem-break imagem-when a-imagem-n%C3%a3o-load but it’s only with HTML/CSS, there are JS responses there tb that works exactly as you want it

  • i would like to do without javascript, since I am using Razor to build the page.

1 answer

0

You can use the attribute onerror in the tag itself. This attribute will execute a code if there is a failure to load the image, and this code can be changed by src image by the default image you want.

I will put below 2 examples, one with failure and the other without failure:

Flawed

img{
   width: 100px;
   height: 100px;
}
<img src="nada aqui ou um caminho inexistente" onerror="this.src = 'http://www.freeiconspng.com/uploads/error-icon-28.png'">

Flawlessly

img{
   width: 100px;
   height: 100px;
}
<img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" onerror="this.src = 'http://www.freeiconspng.com/uploads/error-icon-28.png'">

Browser other questions tagged

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