HTMLElement: error event - Web APIs | MDN (2024)

The error event is fired on an element 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.

Syntax

Event type

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

html

<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>
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: 0.5rem;}img { width: 0; height: 0;}

JavaScript

js

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");});

Result

Specifications

Specification
UI Events
# event-type-error

Browser compatibility

BCD tables only load in the browser

See also

  • Related events
    • Window: error event
    • HTMLElement: load event
HTMLElement: error event - Web APIs | MDN (2024)
Top Articles
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 5916

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.