
Introduction
When working with images in web development, It's crucial to ensure that the user experience remains intact even if an image fails to load. A broken image can disrupt the aesthetics of your website and provide a poor user experience. To handle this gracefully, you can use JavaScrpit to replace the broken image with a placeholder image and display an appropriate alt text.
Solution 1:
In the example below, if the logo.png image does not exist in the directory, the onerror function will be triggered and will set the image source to default.png :
<img src="logo.png" alt="Product image" onerror="this.onerror=null;this.src='default.png';" />
Solution 2:
Same as above img tag with onEroorImage function In the example below, the broken image will set the by OnErrorImage function:
<img src="logo.png" alt="Product image" onerror="onErrorImage(this)"/>
<script type="text/javascript">
function onErrorImage(element){
element.src = 'default.png'
}
</script>
Solution 3 : (Handling Broken Images)
If you implement Onerror image on all images, so you just need to get all the images and replace them with the default image.
<script type="text/javascript">
document.querySelectorAll('img').forEach(img => {
img.onerror = function() {
this.onerror = null;
this.src = 'default.png'
}
});
</script>
Using Jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('img').each(function(index, element){
$(element).attr('src', 'default.png');
});
</script>
Explanation:
- Onerror Attribute:
- The onerror attribute is used to specify a JavaScript function that runs when an error occurs while loading an image.
- In this case, the function sets the src attribute of the image to default.png if the logo.png fails to load.
- this.onerror=null; ensures that the onerror handler is only executed once, preventing an infinite loop if the default.png image also fails to load.
- The onerror attribute is used to specify a JavaScript function that runs when an error occurs while loading an image.
- Fallback Image:
- Providing a fallback image ensures that your webpage remains visually consistent and informative even when the primary image is unavailable.
- Providing a fallback image ensures that your webpage remains visually consistent and informative even when the primary image is unavailable.
- Why Handle Broken Images?
Broken images can occur for various reasons, such as:- Incorrect URLs
- Server issues
- The image file being deleted or moved
* Please Don't Spam Here. All the Comments are Reviewed by Admin.