Home >Web Front-end >JS Tutorial >How Can I Replace Broken Images with JavaScript or jQuery?

How Can I Replace Broken Images with JavaScript or jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 08:28:10796browse

How Can I Replace Broken Images with JavaScript or jQuery?

Replace Broken Images with jQuery/JavaScript

Broken images can mar the aesthetics of your web pages, leaving users with incomplete or visually unappealing experiences. Fortunately, jQuery and JavaScript offer tools to elegantly handle this issue.

jQuery Approach

While one might initially consider using jQuery to manage broken images, JavaScript provides a simpler, more effective solution. By handling the onError event for each image, you can reassign its source if it fails to load.

JavaScript Solution

The JavaScript code snippet below captures the onError event for an image element, updating its src attribute to display a placeholder image (e.g., "noimage.gif").

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

Alternatively, you can use a more concise syntax without a separate JavaScript function:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

Compatibility

The table below lists the browsers that support the error facility for handling broken images:

https://www.quirksmode.org/dom/events/error.html

The above is the detailed content of How Can I Replace Broken Images with JavaScript or jQuery?. 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