Events

onerror

A resource fails to load, or a script error is reported on Window. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("demo"). Event interface: Event / ErrorEvent. Propagation and cancellation depend on the target and event variant. Element resource errors and Window script errors differ. window.onerror uses five arguments and returning true suppresses default reporting. Example: The image source is set after the listener is registered. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
<img onerror="handleEvent(event)">window.addEventListener("error", event => { /* handle error */ });

Parameters & Attributes

NameTypeDescription
onerrorJavaScript handler bodyOptional handler body on a resource element. Window onerror has special arguments and cancellation behavior; the listener example uses the resource event.
eventEvent / ErrorEventEvent object delivered to the addEventListener callback; event.type is "error". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<img id="demo" alt="Sample image"><p role="status" id="log">Waiting for error</p><script>  const target = document.getElementById("demo");  const log = document.getElementById("log");  target.addEventListener("error", event => {    log.textContent = String(event.type);  });  target.src = "data:image/png;base64,invalid";</script>
HTML Reference