Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onerror — handling an error event

The onerror attribute contains JavaScript that handles an error event, for example when an image fails to load. Element handlers differ from window.onerror in their arguments and in the meaning of their return value.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<img onerror="/* JavaScript using event */" alt="">
element.onerror = function (event) { /* ... */ };
window.onerror = function (message, source, lineno, colno, error) { /* ... */ };

onerror is an event handler attribute for error. Its value is JavaScript code, not a URL. On an ordinary element such as img, the code receives event. The corresponding JavaScript property can be assigned a function or set to null to remove the handler.

window.onerror has a special signature: for an ErrorEvent, it receives message, source, lineno, colno, error. Returning true cancels the event only if it is cancelable, thereby suppressing any default error reporting. A synthetic ErrorEvent is noncancelable by default, so returning true does not cancel it. Returning true does not resume interrupted code. An ordinary element handler uses return false to cancel an event if it is cancelable. A callback passed to addEventListener('error', ...) receives one event object, and its return value does not cancel the event.

On the body element, the onerror attribute handles Window events rather than local errors of the body element. Do not confuse it with resource-error handling on img.

The example dispatches a synthetic error event, so it needs neither network access nor an actual loading failure. With JavaScript enabled and inline handlers permitted, the output element should display error. This tests handler invocation, not image loading.

Examples

<!doctype html>
<meta charset="utf-8">
<title>onerror</title>
<img id="image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Demo" onerror="document.getElementById('result').textContent = event.type;">
<output id="result"></output>
<script>
  document.getElementById('image').dispatchEvent(new Event('error'));
</script>

Result

error

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources