jQuery Error Event

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Browser events

What You’ll Learn

The error event fires when the browser fails to load a resource such as an image. This tutorial covers .on("error"), attaching handlers before src, fallback swapping, .one("error"), .trigger("error"), the official jQuery API demos, and how this differs from load, window.onerror, and the removed .error() method.

01

.on()

Bind handler

02

Before src

Attach first

03

Fallback

Swap image

04

.one()

Run once

05

.trigger()

Fire error

06

Since 1.7

Modern API

Introduction

Broken avatars, missing product photos, and dead CDN links all show the same ugly browser placeholder unless your code catches the failure first. The error event is jQuery’s hook for that moment — when an element such as <img> cannot load its resource.

The official jQuery API distinguishes the error event (bound with .on("error") since 1.7) from the removed .error() method (Ajax shorthand, gone in jQuery 3.0). To programmatically run error handlers, use .trigger("error") since jQuery 1.0.

Understanding the error Event

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly — for example, when the URL returns a 404 or the file is unreachable.

It applies to resource elements the browser loads directly — most commonly <img>, and also <script> and <link> in supporting browsers. It is not the same as catching JavaScript exceptions on window; for script errors, use window.onerror instead.

💡
Beginner Tip

Bind the handler before setting src. Chain .on("error", fn) first, then .attr("src", url) — otherwise the browser may fire error before your handler exists.

📝 Syntax

The modern jQuery API for the error event has two main forms — binding a handler and triggering the event:

1. Bind a handler — .on("error" [, eventData ], handler) (since 1.7)

jQuery
.on( "error" [, eventData ], handler )
  • eventData — optional object passed to the handler as event.data.
  • handler — function called when the resource fails: function( event ) { ... }.

2. Event delegation — .on("error", selector, handler)

jQuery
$( "#gallery" ).on( "error", "img", function( event ) {
  // runs when any img inside #gallery fails to load — including future ones
} );

Attach delegation on a container, then set src on child images — one handler covers dynamic galleries.

3. Trigger the event — .trigger("error") (since 1.0)

jQuery
.trigger( "error" )
  • Runs bound error handlers on the matched element(s).
  • Does not simulate a real network failure — it fires jQuery-bound handlers only.

4. Unbind — .off("error" [, selector] [, handler])

jQuery
$( "#book" ).off( "error" );                 // remove all error handlers
$( "#gallery" ).off( "error", "img", fn );   // remove delegated handler

Official jQuery API examples

jQuery
$( "#book" )
  .on( "error", function() {
    alert( "Handler for `error` called." );
  } )
  .attr( "src", "missing.png" );

$( "#other" ).on( "click", function() {
  $( "#book" ).trigger( "error" );
} );

Return value

  • .on() and .trigger() return the original jQuery object for chaining.
  • Inside the handler, this refers to the DOM element that failed to load — use $(this).attr("src", fallback) to swap images.

⚡ Quick Reference

GoalCode
Bind error handler on image$("#book").on("error", fn)
Attach before setting src.on("error", fn).attr("src", url)
Swap broken image fallback$(this).attr("src", "fallback.png")
Run handler only once$("#avatar").one("error", fn)
Delegate to gallery images$("#gallery").on("error", "img", fn)
Trigger error programmatically$("#book").trigger("error")
Remove error handlers$("#book").off("error")

📋 error vs load vs window.onerror vs deprecated .error()

Four related concepts that sound similar — know which handles broken images, successful loads, script exceptions, and Ajax failures.

error event
img fail

Resource failed to load on an element — bind with .on("error") on <img> before setting src

load event
img ok

Resource loaded successfully — pair with error for complete load/fail handling on images and iframes

window.onerror
JS throw

Uncaught JavaScript exceptions — different API; do not use $(window).on("error") for script errors

.error() method
removed

Old Ajax error shorthand removed in jQuery 3.0 — use .fail() or .ajaxError(), not .on("error") confusion

Examples Gallery

Examples 1–3 follow the official jQuery API documentation. Examples 4–5 extend the pattern with multi-image logging and a one-time SVG fallback. Use the Try-it links to run each snippet in the browser.

📚 Binding & Triggering

Official jQuery demos for error handlers and programmatic triggers.

Example 1 — Official Demo: Bind Handler on #book Before Broken src

Alert when the image fails to load — handler attached before src is set.

jQuery
$( "#book" )
  .on( "error", function() {
    alert( "Handler for `error` called." );
  } )
  .attr( "src", "missing.png" );
Try It Yourself

How It Works

Chaining .on("error", fn) before .attr("src", ...) guarantees the handler exists when the browser reports the failure. Reversing the order can miss the event entirely.

Example 2 — Official Demo: Replace All Broken Images with a Fallback

Swap src inside the error handler when any thumbnail fails — from the jQuery API documentation.

jQuery
// If missing.png is missing, it is replaced by replacement.png
$( "img" )
  .on( "error", function() {
    $( this ).attr( "src", "replacement.png" );
  } )
  .attr( "src", "missing.png" );
Try It Yourself

How It Works

$(this) inside the handler is the failed <img>. Setting a valid replacement src prevents the broken-icon UX — but if the fallback also fails, error fires again in a loop.

Example 3 — Official Demo: #other Triggers Error on #book

One button programmatically fires the error handler on the image.

jQuery
$( "#book" ).on( "error", function() {
  alert( "Handler for `error` called." );
} );

$( "#other" ).on( "click", function() {
  $( "#book" ).trigger( "error" );
} );
Try It Yourself

How It Works

.trigger("error") synthetically fires the event. Bound handlers run, but no actual HTTP failure occurs — ideal for unit tests and demo buttons.

📈 Galleries & Safe Fallbacks

Log multiple failures and use .one("error") with a guaranteed-valid SVG placeholder.

Example 4 — Log Failures for Multiple Gallery Images

Bind an error handler per image and log each failure with a data id — practical for debugging CDN issues.

jQuery
$( ".gallery img" ).each( function() {
  var $img = $( this );
  $img.on( "error", function() {
    $( "#log" ).append(
      "<div>error on id=" + $img.data( "id" ) +
      " (" + $img.attr( "alt" ) + ")</div>"
    );
  } ).attr( "src", "missing-" + $img.data( "id" ) + ".png" );
} );
Try It Yourself

How It Works

Looping with .each() lets you bind and set src per image while closing over each $img reference. For many dynamic images, prefer delegation on the gallery container instead.

Example 5 — .one("error") with Inline SVG Fallback

Run the handler once, swap to a data-URI SVG that always loads, and avoid infinite error loops.

jQuery
var fallbackSvg = "data:image/svg+xml," + encodeURIComponent(
  '<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96">' +
  '<rect fill="#e2e8f0" width="96" height="96"/>' +
  '<text x="48" y="54" text-anchor="middle" fill="#64748b" font-size="12">User</text>' +
  '</svg>'
);

$( "#avatar" )
  .one( "error", function() {
    $( this ).attr( "src", fallbackSvg );
  } )
  .attr( "src", "missing-avatar.png" );
Try It Yourself

How It Works

.one("error") automatically unbinds after the first call. Inline SVG via data: URI cannot 404, so the handler never re-fires — the safest avatar fallback pattern.

🚀 Common Use Cases

  • Broken image placeholders — swap to a default avatar or “image unavailable” graphic when CDN links die.
  • User-uploaded content — catch failed profile photos and show a generic silhouette.
  • Product galleries — log which SKUs have missing images for admin dashboards.
  • Lazy-loaded thumbnails — attach error handlers before setting deferred src values.
  • Graceful degradation — hide broken <script> or stylesheet failures with paired error handlers where supported.
  • Testing fallback UI — use .trigger("error") to verify handler logic without breaking real URLs.

🚀 How the error Event Flows

1

Handler attached, src set

Code chains .on("error", fn) then .attr("src", url) — or sets src in HTML after binding in a script block.

bind first
2

Browser requests resource

The browser fetches the URL over HTTP/HTTPS. A 404, network error, or invalid response means the element did not load correctly.

fetch
3

error event fires

jQuery runs your handler. Inside it, this is the failed element — swap src, log the failure, or show a message.

error
4

Fallback or done

Valid replacement src loads successfully, or .one() removes the handler. Bad fallbacks trigger error again — avoid infinite loops.

📝 Notes

  • Bind with .on("error", handler) since jQuery 1.7 — not the removed .error() Ajax method.
  • Trigger with .trigger("error") since jQuery 1.0.
  • Attach the handler before setting src — the official API requirement.
  • The file: protocol often does not fire error reliably — test over HTTP/HTTPS.
  • Do not bind jQuery error on window for script errors — use window.onerror.
  • Ensure fallback images exist — otherwise error loops indefinitely.
  • Use .one("error") or inline data: URIs for safe one-shot fallbacks.
  • Use .off("error") to remove handlers — avoid deprecated .unbind("error").

Browser Support

The error event is a standard DOM event on resource elements such as <img>, supported in every browser jQuery targets. jQuery’s .on("error") (since 1.7) and .trigger("error") (since 1.0) provide consistent binding and chaining. Requires HTTP/HTTPS for reliable firing — not file: local pages.

jQuery 1.7+

jQuery error event

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery versions. Native equivalent: element.addEventListener('error', fn) — jQuery adds collection binding, eventData, delegation, and .trigger() in one chainable API.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
error Universal

Bottom line: Safe in any jQuery project. Prefer .on('error') over the removed .error() method. Bind before src and use valid fallbacks.

Conclusion

The jQuery error event is the standard hook for broken images and other failed resource loads. Bind handlers with .on("error", fn) before setting src, swap to valid fallbacks inside the handler, and fire handlers programmatically with .trigger("error").

Remember: this is not window.onerror for JavaScript exceptions, and it is not the removed .error() Ajax shorthand. For dynamic galleries, delegate with $("#gallery").on("error", "img", fn) and always test over HTTP — not file:.

💡 Best Practices

✅ Do

  • Bind with .on("error", handler) before setting src
  • Use guaranteed-valid fallbacks — inline SVG data: URIs are safest
  • Use .one("error") when swapping src once
  • Delegate on gallery containers for dynamic images
  • Test over http:// or https://, not file:

❌ Don’t

  • Confuse with removed .error() — that was for Ajax, not images
  • Attach jQuery error on window for script exceptions
  • Set fallback src to another broken URL — infinite loop
  • Set src before binding the handler — event may be missed
  • Expect reliable error on locally opened file: pages

Key Takeaways

Knowledge Unlocked

Six things to remember about the error event

Bind, load, fallback.

6
Core concepts
src 02

Before src

Attach first

Order
🖼 03

Fallback

Swap img

Recover
1x 04

.one()

No loop

Safe
05

.trigger()

Test UI

Programmatic
win 06

Not window

onerror

Separate

❓ Frequently Asked Questions

The browser fires the error event as soon as it fails to load a resource. If you set src before binding .on('error', handler), the failure may happen before your handler exists and the event is missed. Chain .on('error', fn) first, then .attr('src', url) — the official jQuery API pattern for #book and broken images.
The error event relies on HTTP status codes from a network request. Pages opened locally with file: often behave differently — the browser may not report a failed load the same way. Test over http:// or https://, including the Try-it labs on this site.
The jQuery error event on elements such as img fires when that resource fails to load. window.onerror (or window.addEventListener('error', ...)) handles uncaught JavaScript exceptions and uses different arguments and return-value rules. Do not attach jQuery .on('error') to window for script errors — use window.onerror instead.
If the replacement src also fails to load, the error handler runs again forever. Ensure the fallback URL is valid and loads successfully. Use .one('error') to run the handler once, or .off('error') after swapping. Inline data: URIs or guaranteed-valid SVG placeholders are safe fallbacks.
They target the same browser error event on elements such as images — .error(handler) was the legacy shorthand removed in jQuery 3.0, while .on('error', handler) is the modern replacement since 1.7. Do not confuse this with Ajax .fail() or global window.onerror for JavaScript exceptions.
Call $('#book').trigger('error') since jQuery 1.0. Bound error handlers run on the matched element. This is useful for testing fallback UI without forcing a real network failure — the official API demo uses #other click to trigger error on #book.
Did you know?

The jQuery API page for error warns that if replacement.png is also missing, the handler runs again — and again — forever. That is why production sites often use .one("error") or inline data:image/svg+xml placeholders: they load without a network request, so the event cannot recurse. The same page also notes that file: URLs may never fire error at all because the event depends on HTTP status codes.

Next: jQuery .error() Method

Legacy shorthand removed in jQuery 3.0 — learn migration to .on("error").

.error() method 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.

6 people found this page helpful