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
Release: 2024-11-27 02:21:14
Original
898 people have browsed it

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

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

Then, assign this class to the image:

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

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();
});
Copy after login

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!

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