Execute a script when an error occurs in HTML?


In this article we are going to learn about how to execute a script when an error occurs in HTML.

If an error happens while loading an external file, the onerror event is started (e.g. a document or an image).

Let’s look into the following examples to understand more about how to execute a script when an error occurs in HTML.

Using HTML

Example

In the following example we are using img to get displayed on our webpage using img src.

<!DOCTYPE html>
<html>
<body>
   <img src="C:\Users\Lenovo\Desktop\Tutorialspoint\12.png" onerror="mytutorial()">
   <p id="varma"></p>
   <script>
      function mytutorial() {
         document.getElementById("varma").innerHTML ="Image cannot be loaded.";
      }
   </script>
</body>
</html>

On executing the above script, the img src was checked and displayed with the text "image cannot be loaded" as an error event was triggered.

Using addEventListener() method

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. The method addEventListener() works by adding a function, or an object that implements EventListener, to the list of event listeners for the specified event type on the EventTarget on which it's called.

Example

Considering the following example we are using eventlistener() method for the image source to get displayed.

<!DOCTYPE html>
<html>
<body>
   <img id="tutorial" src="C:\Users\Lenovo\Desktop\Tutorialspoint\12.png">
   <p id="tutorial1"></p>
   <script>
      document.getElementById("tutorial").addEventListener("error", mytutorial2);
      function mytutorial2() {
         document.getElementById("tutorial1").innerHTML = "Image cannot be loaded.";
   }
   </script>
</body>
</html>

When the script gets executed, the method gets triggered and searches for an image source If the image source was not found, the error event occurs and displays the text "image cannot be loaded."

Updated on: 15-Dec-2022

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements