Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-03 18:34:29
Original
847 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template