Home > Article > Web Front-end > Why Does the `onerror` Attribute for Images Sometimes Fail in Chrome and Mozilla?
Handling Broken Images with the onerror Attribute
The HTML element provides an onerror attribute that allows developers to specify an alternative image or action to be taken if the primary image fails to load. However, users have reported encountering issues with this attribute in certain browsers like Chrome and Mozilla.
To resolve this issue, it is recommended to use the following code structure:
<code class="html"><img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';" ></code>
This code works by setting the onerror handler to null after triggering the first time. This prevents an infinite loop of error events in case the backup URL is also invalid.
Live Demo: http://jsfiddle.net/oLqfxjoz/
The above is the detailed content of Why Does the `onerror` Attribute for Images Sometimes Fail in Chrome and Mozilla?. For more information, please follow other related articles on the PHP Chinese website!