Skip to content
Related Articles

Related Articles

Improve Article

HTML | DOM onerror Event

  • Last Updated : 30 Jul, 2021

The HTML DOM onerror event is triggered when an interruption occurs while loading an external file.
Some events that occur if there is some kind of disturbance to the media loading process, are: 

  • onabort
  • onemptied
  • onstalled
  • onsuspend

Supported Tags

  • <img>
  •  <input type=”image”>
  • , <object>
  •  <link>
  •   <script>

Syntax:

In HTML:  

<element onerror="myScript">

In JavaScript:  



object.onerror = function(){myScript};

In JavaScript, using the addEventListener() method:  

object.addEventListener("error", myScript);

Example: Using HTML 

HTML




<!DOCTYPE html>
<html>
 
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
        <h2>HTML DOM onerror event</h2>
        <img src="image.gif" onerror="gfgFun()">
 
        <script>
            function gfgFun() {
                alert('Error!!');
            }
        </script>
    </center>
</body>
 
</html>

Output: 
 

 

Example: Using JavaScript 

HTML




<!DOCTYPE html>
<html>
 
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
        <h2>HTML DOM onerror event</h2>
 
        <img id="logo" src="image.gif">
 
        <p id="try"></p>
 
 
 
        <script>
            document.getElementById(
              "logo").onerror = function() {
                myFunction()
            };
 
            function myFunction() {
                document.getElementById(
                  "try").innerHTML = "Error!!";
            }
        </script>
    </center>
</body>
 
</html>

Output: 
 



Example: Using the addEventListener() method 

HTML




<!DOCTYPE html>
<html>
 
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
        <h2>HTML DOM onerror event</h2>
 
        <img id="logo" src="image.gif">
 
        <p id="try"></p>
 
 
 
        <script>
            document.getElementById(
              "logo").addEventListener("error", myFunction);
 
            function myFunction() {
                document.getElementById(
                  "try").innerHTML = "Error!!";
            }
        </script>
    </center>
</body>
 
</html>

Output: 
 

Supported Browsers: The browsers supported by HTML DOM onerror Event are listed below: 

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera

 

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :