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.
| Bubbles | No |
|---|---|
| Cancelable | No |
| Interface | Event or UIEvent |
| Event handler property | onerror |
The event object is a UIEvent instance if it was generated from a user interface element, or an Event instance otherwise.
Examples
Live example
HTML
<div class="controls"> <button id="img-error" type="button">Generate image error</button> <img class="bad-img" /> </div> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div>
CSS
body {
display: grid;
grid-template-areas: "control log";
}
.controls {
grid-area: control;
display: flex;
align-items: center;
justify-content: center;
}
.event-log {
grid-area: log;
}
.event-log-contents {
resize: none;
}
label, button {
display: block;
}
button {
height: 2rem;
margin: .5rem;
}
img {
width: 0;
height: 0;
}
JS
const log = document.querySelector('.event-log-contents');
const badImg = document.querySelector('.bad-img');
badImg.addEventListener('error', (event) => {
log.textContent = 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');
});
Result
Specifications
| Specification | Status |
|---|---|
| UI Events | Working Draft |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
error event | Chrome Full support Yes | Edge Full support ≤79 | Firefox Full support Yes | IE ? | Opera ? | Safari ? | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android ? | Safari iOS ? | Samsung Internet Android Full support Yes |
Legend
- Full support
- Full support
- Compatibility unknown
- Compatibility unknown
See also
- This event on
Windowtargets:errorevent
