How to replace an image load failed by default image in Javascript?

When an image load failed, nothing to show after that, that may affect to UI/UX and make user confusing.
What will you do in this case? I will replace a default image, maybe is an image "No image found" like this:



So, how I can do that? So easy! Let me show you now:

Write a function like this:

function onImgError(e) {
 e.src = 'no-image-found.jpg';
}

The function will replace the src of error image by a default image you want to show.


Usage:
Use onerror event to call the function when it can't load



Note: don't forget pass this into the function

© 2019 4codev

Created with love by Sil.