Home  >  Article  >  Web Front-end  >  Why Does the `onerror` Attribute for Images Sometimes Fail in Chrome and Mozilla?

Why Does the `onerror` Attribute for Images Sometimes Fail in Chrome and Mozilla?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 18:34:29786browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn