HTML onerror Attribute

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

Definition and Usage

The onerror attribute is an event-handler attribute. It runs JavaScript when the error event fires — a resource failed to load or cannot be used (for example a missing image, a blocked script file, or media the browser cannot decode).

Common on <img>, <script src>, <audio>, and <video>. Related: onload (success) and onabort (load canceled). This is not the same as window.onerror (uncaught script errors).

Baseline · Widely available.

Not deprecated and not experimental. Per MDN, element error is not cancelable and does not bubble. Stable since about July 2015.

Discouraged as inline HTML.

MDN discourages HTML event handler attributes. Prefer el.addEventListener("error", handler) in production; use inline onerror for quick demos and learning.

HTML Syntax

syntax.html
<img|script|… onerror=" script">

script is JavaScript that runs on load failure. Equivalent JS: el.onerror = handler or el.addEventListener("error", handler).

Attribute Values

The attribute value is always a script. Common patterns:

Value / patternDescriptionTry it
scriptAny JavaScript run when the resource failsTry it
onerror="fn(this)"Call a named function; pass the element as thisTry it
addEventListener("error")Preferred modern listener — clear handler before swapping srcTry it
One-liner + nullthis.onerror=null;this.src='…' prevents infinite fallback loopsTry it

Live Preview

Click Load broken image to fire error. The handler swaps to a working placeholder and updates the status.

Actions

Broken URL triggers error; fallback uses /images/codetofun-logo.png.

Preview
Demo image

Ready — try a broken load.

HTML Examples

Short, copy-ready snippets. Use Try It Yourself for a live editor.

Example 1 — Image Fallback with onerror

Swap a broken src for a placeholder and update status.

HTML
<img id="photo" src="/images/__missing__.webp" alt="Product photo"
     onerror="handleImageError(this)">
<p id="status">Loading image…</p>

<script>
  function handleImageError(img) {
    document.getElementById("status").textContent =
      "error — swapping to fallback.";
    img.onerror = null;
    img.src = "/images/codetofun-logo.png";
    img.alt = "Placeholder image";
  }
</script>
Try It Yourself

How It Works

  1. Broken src — the browser cannot load the image.
  2. error fires on the <img> and runs onerror.
  3. Set onerror = null before changing src so a bad fallback cannot loop forever.
  4. Assign a working src and keep alt meaningful for accessibility.

Example 2 — Prefer addEventListener

Same fallback, with a modern listener instead of an inline attribute.

HTML
<img id="avatar" src="/images/__missing-avatar__.webp" alt="Avatar">
<p id="log">Waiting for error…</p>

<script>
  var img = document.getElementById("avatar");
  var log = document.getElementById("log");

  function onImgError() {
    log.textContent = "error fired — using placeholder.";
    img.removeEventListener("error", onImgError);
    img.src = "/images/codetofun-logo.png";
    img.alt = "Default avatar";
  }

  img.addEventListener("error", onImgError);
</script>
Try It Yourself

How It Works

  1. Listen for error with addEventListener.
  2. Update UI when the load fails.
  3. Remove or clear the handler before swapping src (avoids a loop).
  4. Load the fallback — if that succeeds, load fires instead of another error.

Example 3 — Compact One-liner Fallback

Clear the handler and set src in one attribute value.

HTML
<img src="/images/__broken__.webp" alt="Thumbnail"
     onerror="this.onerror=null;this.src='/images/codetofun-logo.png';this.alt='Placeholder'">
<p>If the first URL fails, the placeholder appears.</p>
Try It Yourself

How It Works

  1. this is the <img> that failed.
  2. this.onerror = null disables further error callbacks on this element.
  3. this.src = '…' requests the fallback file.
  4. Keep it short — for larger logic, use a named function or addEventListener.

Edge Cases & Pitfalls

Most “page froze” bugs are an onerror that keeps swapping to another bad URL.

loop

Infinite fallback loop

If the fallback src also fails, error fires again. Set onerror = null (or remove the listener) before changing src.

abort

Not the same as abort

Canceled loads use onabort. Failed loads use error.

window

Not window.onerror

Element onerror is for resource load failures. window.onerror targets uncaught script errors and has a special multi-argument signature on Window.

api

Not cancelable

You cannot stop element error with preventDefault(). Recover in the handler (fallback UI, logging).

a11y

Update alt after swap

When you change src to a placeholder, set a clear alt so assistive tech describes the image the user actually sees.

Browser Support

onerror is an HTML event-handler attribute for resource elements in the browser. It is not a Node.js, Deno, or Bun API.

✓ Baseline · Widely available

onerror

Widely available since about July 2015. Chrome, Firefox, Safari, Edge, and Opera support error on img, script, and media.

97% Global support (approx.)
Google Chrome All modern
Full support
Mozilla Firefox All modern
Full support
Apple Safari All modern
Full support
Microsoft Edge All modern
Full support
Opera All modern
Full support
Samsung Internet Modern
Full support
Internet Explorer 9+
Supported
onerror Widely supported

Bottom line: Safe to use for image/script/media failure UX. Prefer addEventListener('error') in apps, and always clear the handler before swapping src.

Key Takeaways

  • Role: resource failed to load or cannot be used.
  • Not cancelable and does not bubble.
  • Clear the handler before changing src to avoid loops.
  • Not onabort and not window.onerror.

One line: onerror means the resource failed — clear the handler, then show a fallback.

Frequently Asked Questions

It is an event-handler attribute. When a resource fails to load or cannot be used (broken image URL, missing script, media decode/network failure), the error event fires and the JavaScript in onerror runs.
Elements that load external resources — commonly img, script (with src), audio, video, link, and track. Put the handler on the element that owns the resource URL.
No. Per MDN, the element error event is not cancelable and does not bubble. You react after it fires (for example swap img.src).
onerror means the load failed. onabort means the load was canceled before it finished. They are different events.
No. Element onerror handles resource load failures on that element. window.onerror is a special Window handler for uncaught script errors (different signature and behavior).
No. The error event and onerror handler are standard and Baseline widely available since about July 2015. Inline HTML handlers are discouraged in production in favor of addEventListener.

Next: onfocus

Run JavaScript when an element receives focus.

onfocus tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful