Languages
[Edit]
EN

HTML - display text message when image is not loaded correctly

3 points
Created by:
Kevin
367

In this article, we would like to show you how to display text message when the image is not loaded correctly in HTML.

Quick solution:

// ONLINE-RUNNER:browser;

<img src="https://wrong-url.com/image.png" alt="Error message." />

There are many reasons that may cause image loading errors: incorrect URL, network connection problems, incorrect server configuration, incorrect image file.

 

Practical example

In this example, we display text message when the image isn't loaded correctly using alt attribute. The message about loading error is displayed in the console too using onerror event.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>
    
    function handleError(image) {
      	console.error('Image loading error (' + image.src + ').');
    }
    
  </script>
  <img src="https://wrong-url.com/image.png"
       alt="Image loading error." 
       onerror="handleError(this)" />
</body>
</html>

References

  1. <img>: The Image Embed element - HTML | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join