Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onerror event using background: url()

Is there a way to show alternate image if source image is not found? I know to accomplish this is by doing something like below:

<img src="imagenotfound.gif" alt="Image not found" onError="this.src='imagefound.gif';" /> 

But how about if you are doing something like this, how can you catch if there is an error or if the image is not found?

<div style="background:url('myimage.gif')"></div> 
like image 862
Bono Avatar asked Mar 09 '14 20:03

Bono


2 Answers

In case myimage.gif isn't transparent, you could use multiple backgrounds:

background: url('myimage.gif'), url('fallback.gif'); 

This way fallback.gif will only be visible if myimage.gif isn't available.

Note that fallback.gif may be downloaded even if myimage.gif is available.


Alternatively, even though not widely supported, CSS Images 3 introduces the image() notation:

background: image('myimage.gif', 'fallback.gif'); 

Multiple <image-decl>s can be given separated by commas, in which case the function represents the first image that's not an invalid image.

like image 113
Oriol Avatar answered Oct 06 '22 00:10

Oriol


With background images, there is no event; you have check yourself.

Make an (XML)HTTP request, and if you get a response with an error status code or no response at all (after timeout), use another image resource. This approach is limited by the Same-Origin Policy.

like image 39
PointedEars Avatar answered Oct 06 '22 01:10

PointedEars