The error event fires on elements (commonly <img>) when the browser fails to load that resource. Bind with .on("error", handler) (since 1.7) and trigger with .trigger("error").
Syntax
Start with these common calls. Keep them short and readable.
jQuery
$("#book")
.on("error", function () {
// resource failed to load
})
.attr("src", "missing.png"); // bind BEFORE setting src
// Trigger for tests:
$("#book").trigger("error");
// Do NOT: $(window).on("error", …) for script errors
Call
What it does
error
Learn jQuery error event: bind .on(\
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Select the element (usually an <img>).
Step 2
Attach .on("error", handler) before changing src.
Step 3
Set src (or let the browser load a broken URL).
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
jQuery Examples
Example 1 — Bind Before Setting src
Official pattern: attach error first, then load a missing image.
jQuery
$("#book")
.on("error", function () {
$("#log").text("Handler for error called.");
})
.attr("src", "missing.png");
Swap.$(this).attr("src", fallback) replaces the broken URL.
Safe. A data: SVG cannot 404, so the handler does not loop.
Example 3 — .trigger("error")
Official demo: fire the handler from a button without a real network failure.
jQuery
$("#book").on("error", function () {
$("#log").text("Handler for error called.");
});
$("#other").on("click", function () {
$("#book").trigger("error");
});
Synthetic. Handlers run without a failed network load.
Frequently Asked Questions
The error event is sent to elements such as images that the browser failed to load correctly. Bind with .on("error", handler) (since 1.7). It is a browser resource-load event — not an Ajax failure callback and not window.onerror for script exceptions.
The browser can fire error as soon as loading fails. If you set src before .on("error"), you may miss the event. Official pattern: chain .on("error", fn) first, then .attr("src", url).
error relies on HTTP-style load failure reporting. Pages opened as file: often behave differently. Test over http:// or https://.
No. Do not attach a jQuery error handler to window for script errors. The window error event uses different arguments and return-value rules. Use window.onerror (or window.addEventListener("error", …)) instead.
If the replacement src also fails, error fires again. Ensure the fallback is valid, or use .one("error") / .off("error") after swapping. Inline data: SVG placeholders are safe because they cannot 404.
No. The .error() shorthand was deprecated in 1.8 and removed in jQuery 3.0. Use .on("error", handler) and .trigger("error") instead.
Call $(element).trigger("error"). Bound handlers run without a real network failure — useful for testing fallback UI.