Last active
June 23, 2020 03:42
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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