Improve your skills

June 17, 2016

How to Show Alternate Image if Source Image is Not Found

The simple way to solve the problem-

By set the another image path in onError attribute of image, we resolve the problem. When the source image is not found then onError event fire and then it change source with another image. Use image tag described as below-

<img src="imageNotFound.jpg" alt="Image not found" onError="this.src='alternateImage.jpg';" />

If the alternate image is also not found then the browser will be go in an endless loop. onerror itself generates an error. To avoid endless loop, remove the onError from it at once.

<img src="imageNotFound.jpg" alt="Image not found" onError="this.onerror=null; this.src='alternateImage.jpg';" />

By calling this.onerror=null; 
It will remove the onError then try to get the alternate image and second time onError not call. 

0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts