Open In App

HTML onerror Event Attribute

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

HTML




<!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:

Screenshot-2023-12-14-123900

OUTPUT

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

html




<!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: 

Screenshot-2023-12-14-123623

OUTPUT

Supported Browsers:

  • Google Chrome 1
  • Edge 12
  • Firefox 1
  • Opera 1
  • Safari 12.1


Last Updated : 26 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads