Home >Web Front-end >CSS Tutorial >How Can I Hide Broken Image Icons Using JavaScript, jQuery, or CSS?

How Can I Hide Broken Image Icons Using JavaScript, jQuery, or CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 02:21:14954browse

How Can I Hide Broken Image Icons Using JavaScript, jQuery, or CSS?

Silently Hiding "Image Not Found" Icons with JavaScript/jQuery/CSS

When images are missing from a rendered HTML page, the default "Image not found" icon can be distracting and disrupt the user experience. Fortunately, there are several methods to hide this icon using various technologies.

JavaScript/jQuery

The simplest method involves using the onerror event handler. When an image fails to load, the onerror event is triggered, allowing you to execute a custom action. One such action is to hide the image:

<img onerror="this.style.display = 'none';" src="path/to/image.png">

CSS

CSS offers a more straightforward approach by defining a specific style for images that fail to load. Using the display property, you can set the visibility of the image to hidden:

img.hide-if-failed {
    display: none;
}

Then, assign this class to the image:

<img class="hide-if-failed" src="path/to/image.png">

Using JavaScript/jQuery to Hide Other Elements

If the "Image not found" icon is contained within another element, such as a div, you can use JavaScript or jQuery to hide the parent element when the image fails to load:

$('img').on('error', function() {
  $(this).parent().hide();
});

The above is the detailed content of How Can I Hide Broken Image Icons Using JavaScript, jQuery, or CSS?. 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