CSS Portal

HTML onerror Event Attribute

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
onerror
HTML Event AttributeThis event attribute is supported by all modern browsers.
Updated 14th October 2023

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>
Open in editor

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
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee