Skip to content

Instantly share code, notes, and snippets.

@pzi
Last active June 23, 2020 03:42
Show Gist options
  • Save pzi/e605acd588ddf808554da4fa94da4e5e to your computer and use it in GitHub Desktop.
Save pzi/e605acd588ddf808554da4fa94da4e5e to your computer and use it in GitHub Desktop.
Fallback image display if the original src errors (i.e. 404) - http://jsfiddle.net/pezzi/j9Ls2v5r/
function fallbackImage(el) {
if (el.hasAttribute('data-fallback-url')) {
el.onerror = null; // resetting the error so avoid an endless loop
el.src = el.getAttribute('data-fallback-url'); // update the src
el.alt = el.getAttribute('data-fallback-alt') || '' // update the `alt` attribute for a11y
}
}
<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">
<img src="https://placeimg.com/200/300/animals" alt="My cool image" srcset="path/to/actual/image" />
<img src="invalid_link" alt="Original alt" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';this.alt='new alt'">
<img
src="invalid_link"
alt="Original alt"
data-fallback-url='https://placeimg.com/200/300/animals'
onerror="fallbackImage(this)">
<img
src="invalid_link"
alt="Original alt"
data-fallback-url='https://placeimg.com/200/300/animals'
data-fallback-alt="New alt"
onerror="fallbackImage(this)">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment