Categories
JavaScript Answers

How to handle HTML image not found with JavaScript?

Spread the love

You can handle the scenario where an HTML image fails to load by attaching an event listener to the error event of the <img> element. This event is triggered when the image fails to load.

To do this, we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Handle Image Not Found</title>
</head>
<body>
    <!-- Image element -->
    <img id="myImage" src="nonexistent.jpg" alt="Image">

    <script>
        // Get the image element
        var img = document.getElementById('myImage');

        // Attach error event listener
        img.addEventListener('error', function() {
            console.log('Image not found.');
            // You can perform any action here when the image fails to load
            // For example, you can display a default image or show an error message.
        });
    </script>
</body>
</html>

In this example, we have an <img> element with the ID myImage and a src attribute pointing to a non-existent image file (nonexistent.jpg).

We use JavaScript to get a reference to the image element with document.getElementById('myImage').

Then we attach an event listener to the error event of the image element using the addEventListener method. Inside the event listener function, we handle the scenario where the image fails to load.

In this example, we log a message to the console, but you can perform any action you want, such as displaying a default image or showing an error message.

This way, you can gracefully handle situations where an image fails to load on your webpage.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *