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
Fundamentals
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 errorevent (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.
Concept
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.
Foundation
📝 Syntax
The modern jQuery API for the error event has two main forms — binding a handler and triggering the event:
.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.
Cheat Sheet
⚡ Quick Reference
Goal
Code
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")
Compare
📋 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
Hands-On
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.
Page loads → browser requests missing.png → 404
error event fires → alert: Handler for error called.
Handler must be bound before .attr("src") runs
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" );
Both thumbnails request broken URLs → error fires on each
Handler sets src to valid fallback → placeholder images appear
Log shows "Replaced: Photo A" and "Replaced: Photo B"
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.
Image loads normally with valid src
Click Trigger the handler → trigger("error") → handler runs
Useful for testing fallback UI without a real network failure
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.
Three gallery images request broken URLs
Log fills with:
error on id=1 (Item 1)
error on id=2 (Item 2)
error on id=3 (Item 3)
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.
Broken avatar URL → error fires once
Handler swaps to inline SVG data URI → gray "User" placeholder
.one() removes handler → no loop even if something else fails later
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.
Applications
🚀 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.
Use .one("error") or inline data: URIs for safe one-shot fallbacks.
Use .off("error") to remove handlers — avoid deprecated .unbind("error").
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
errorUniversal
Bottom line: Safe in any jQuery project. Prefer .on('error') over the removed .error() method. Bind before src and use valid fallbacks.
Wrap Up
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:.
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
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about the error event
Bind, load, fallback.
6
Core concepts
.on01
.on("error")
Bind
API
src02
Before src
Attach first
Order
🖼03
Fallback
Swap img
Recover
1x04
.one()
No loop
Safe
⚡05
.trigger()
Test UI
Programmatic
win06
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.