The error
event is fired on an Element
object when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
This event is not cancelable and does not bubble.
The error
event is fired on an Element
object when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
This event is not cancelable and does not bubble.
Use the event name in methods like addEventListener()
, or set an event handler property.
addEventListener("error", (event) => {}); onerror = (event) => {};
The event object is a UIEvent
instance if it was generated from a user interface element, or an Event
instance otherwise.
<div class="controls"> <button id="img-error" type="button">Generate image error</button> <img class="bad-img" /> </div> <div class="event-log"> <label for="eventLog">Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog"></textarea> </div>
const log = document.querySelector(".event-log-contents"); const badImg = document.querySelector(".bad-img"); badImg.addEventListener("error", (event) => { log.textContent += `${event.type}: Loading image\n`; console.log(event); }); const imgError = document.querySelector("#img-error"); imgError.addEventListener("click", () => { badImg.setAttribute("src", "i-dont-exist"); });
Specification |
---|
UI Events # event-type-error |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
error_event |
1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
Window
targets: error
event
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/error_event