HTML onerror Event Attribute

Description

The onerror HTML event attribute is fired when an error occurs while loading an external file, such as an image, script, or CSS file. It can also be used to handle errors that occur in JavaScript code.

To use the onerror attribute, simply add it to the element that is loading the external file or executing the JavaScript code. The value of the attribute should be a JavaScript function that will be called when an error occurs.

Here is an example of how to use the onerror attribute to handle errors that occur while loading an image:

<img src="image.jpg" onerror="handleError()">

The handleError() function will be called if there is an error loading the image.jpg file.

The onerror attribute can also be used to handle errors that occur in JavaScript code. To do this, simply add the attribute to the <script> tag that contains the JavaScript code.

Here is an example of how to use the onerror attribute to handle errors that occur in a JavaScript function:

<script onerror="handleError()">
function myFunction() {
  // Code that may generate an error
}
</script>

The handleError() function will be called if there is an error in the myFunction() function.

The onerror event attribute is a powerful tool for handling errors in your web applications. By using it, you can prevent errors from crashing your application and provide a better user experience.

Syntax

<element onerror="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onerror event</title>
</head>
<body>
<img src="error.jpg" onerror="testFunction(this)">
<script>
function testFunction(source) {
source.onerror = null;
source.src = "sunset.jpg";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onerror Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023