Open In App

HTML onerror Event Attribute

The onerror event works when an error occurs while loading an external file. The external file may contain a document file or an image file.

It simply activates when an error occurs during the loading of an external resource and It is commonly used to handle issues with image loading, script execution, or other external file errors.



Syntax: 

<element onerror = "script">

Supported Tags

Attribute Value:

This attribute contains a single value script that works when onerror event attribute call.

Example 1: In this example first we will see the what will be print on console if lmage is loaded.






<!DOCTYPE html>
<html>
 
<head>
    <title>onerror event attribute</title>
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <img src=
         onerror="myFunction()">
    <h1>GeeksforGeeks</h1>
    <h2>onerror event attribute</h2>
    <script>
        function myFunction() {
            console.log("The image could not be loaded")
        }
    </script>
</body>
 
</html>

Output:

OUTPUT

Example 2: In this example, we will see the implementation of onerror event when an image is not loaded with an example.




<!DOCTYPE html>
<html>
 
<head>
    <title>onerror event attribute</title>
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <img src="image.gif"
         onerror="myFunction()">
    <h1>GeeksforGeeks</h1>
    <h2>onerror event attribute</h2>
    <script>
        function myFunction() {
            console.log("The image could not be loaded")
        }
    </script>
</body>
 
</html>

Output: 

OUTPUT

Supported Browsers:


Article Tags :