Repair Broken Pictures in HTML



Images play an important role in increasing user interest in content and enriching the appearance of websites. However, when it comes to broken images it's important to note that they aren't necessarily a result of an intentional act but can be caused by a myriad of things including wrong links, missing images, and server problems. These are important to avoid any mayhem as it does affect the user experience in very sensitive ways.

In this article we are having a broken image. Our task is to repair broken pictures in HTML.

Approaches to repair broken pictures

Using alt attribute

The alt attribute provides a brief text message that will appear if the image cannot be downloaded.

  • The image is inserted in the HTML document using img tag.
  • The alt attribute provides that even though the image cannot be loaded, the user gets the text description of it.

Example

Here is the given HTML Code for the Alt text technique in images.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Handling Example</title>
<style>
   h1 {
      color: darkblue;
   }
</style>
</head>
<body>
<h1>TutorialsPoint</h1>
<h2>Dealing with Missing Images</h2>
<p>If the image fails to load, a fallback description will be shown instead.</p>
<img src="/html/images/test.png" alt="Alternate text for a missing TutorialsPoint image"/>
</body>
</html>

Using onerror Event

The onerror event in HTML is a specification that replaces the current image with a selected image instead in a dynamic manner.

  • The onerror attribute works in response to broken images by loading a default image.
  • This technique also serves to avoid empty spaces on the webpage in case the image does not work again which enhances visual flow.
  • It can also be used if you need to show brand logos or any other images, which belong to the topic if the primary content is absent.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Fallback Example</title>
<style>
   h1 {
      color: #009688;
   }
   img {
      border: 2px dashed gray;
   }
</style>
</head>
<body>
<h1>TutorialsPoint</h1>
<h2>Alternate Image on Error</h2>
<p>If the main image doesn't load, an alternative image will be displayed.</p>
<img src="/html/images/test.png" alt="Main TutorialsPoint Image" onerror="this.src='/plsql/images/plsql-mini-logo.jpg';"/>
</body>
</html>

Conclusion

In this article to repair broken pictures in HTML we have used two different approaches. These approaches are: by using the alt attribute that explains the image in detail and by using onerror event which allows you to provide a secondary image in case primary image fails to load.

Updated on: 2025-01-28T13:05:53+05:30

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements