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

How Can I Replace Broken Images with jQuery or Plain JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 21:58:14163browse

How Can I Replace Broken Images with jQuery or Plain JavaScript?

Replacing Broken Images with jQuery

Having broken images displayed on a web page can be frustrating for users. Fortunately, JavaScript provides various methods to handle this issue.

One approach is to utilize jQuery's filtering capabilities to identify and replace broken images. To do this:

  1. Use jQuery's $("img") selector to get all images on the page.
  2. Filter the image set using the .error() function to identify broken images.
  3. For each broken image, replace the src attribute with the desired replacement image, such as a default "no image" placeholder.

However, for simplicity, it's often easier to use pure JavaScript to handle broken images.

JavaScript Solution:

The onError event can be used to reassign the source attribute when an image fails to load:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}

Implement this function in the HTML:

<img src="image.png" onerror="imgError(this);"/>

Alternatively, the onError event can be handled directly in the HTML without a function:

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

Refer to the following table for browser compatibility with the error facility:

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

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