Horje

How to add a JavaScript if an error occurs when loading an image

A function is triggered if an error occurs when loading the image. The function shows an alert box with a text. In this example we refer to an image that does not exist, therefore the onerror event occurs.
index.html
Example: HTML
<!DOCTYPE html>
<html>
<body>

<img src="https://horje.com/avatar.png" onerror="myFunction()">

<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text. In this example we refer to an image that does not exist, therefore the onerror event occurs.</p>

<script>
function myFunction() {
  alert("The image could not be loaded.");
}
</script>

</body>
</html>

Output should be:

How to add a JavaScript if an error occurs when loading an image



Single Articles
How to add a JavaScript if an error occurs when loading an imageWindow Event Attributes


Related Articles
What is HTML onafterprint Event Attribute Window Event Attributes
What is HTML onbeforeprint Event Attribute Window Event Attributes
What is HTML onbeforeunload Event Attribute Window Event Attributes
What is HTML onerror Event Attribute Window Event Attributes
What is HTML onhashchange Event Attribute Window Event Attributes
What is HTML onload Event Attribute Window Event Attributes
What is HTML onoffline Event Attribute Window Event Attributes

Type:
Html
Category:
Web Tutorial
Sub Category:
Window Event Attributes
Uploaded by:
Admin