Hello Readers,
When source image is not found then it will show a broken image icon. In today's post we will learn how hide broken image icon when image URL is invalid or not found.
onerror attribute of <img> which executes JavaScript if image URL is invalid or source is not found.
Lets understand with the help of example:
<img src="{{product.imagePath}}" onerror="HideIcon(this);">
<script>
function HideIcon(element)
{
element.style.display = "none";
}
</script>
In the above example image path is coming from server, if URL is invalid or the image is not found then HideIcon() function will be triggered. Which will hide the broken image icon.
We can also set a default image using this onerror attribute for example:
<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">
First set the onerror = null then pass the default image src, this will show the default image if the URL provided is invalid.
Hope this will help you :)
0 Comment(s)