CSS Portal

HTML onerror Event Attribute

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!

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 information will show you the current browser support for the HTML onerror event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.
Desktop
Chrome
Edge
Firefox
Opera
Safari
Tablets & Mobile
Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-

Last updated by CSSPortal on: 14th October 2023

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!