CKTIS / JavaScript
Images in JavaScript: `src`, `alt`, `load`, and `error`
Set an image URL and alternative text, then handle successful and failed image loads using events on the image element.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const img = new Image();
img.alt = text;
img.addEventListener("load", onLoad);
img.addEventListener("error", onError);
// To use handler properties, replace the two listener registrations above with:
// img.onload = onLoad;
// img.onerror = onError;
img.src = url;HTMLImageElement.src/alt/load/error groups two properties and two events of an image element. new Image() creates an img element that starts outside the document tree. This is a web platform API, not part of ECMAScript 2024, so the runtime must provide it.
img.src is a string property that reflects the src attribute. Setting it starts asynchronous image-source processing, even if the element has not been inserted into the document. Reading img.src resolves a valid relative URL against the document’s base URL; img.getAttribute("src") returns the stored attribute value. With responsive image selection, use img.currentSrc to see which URL the browser selected.
img.alt reflects the alt attribute. Write text that conveys the image’s meaning or purpose in context to someone who cannot see it. For a purely decorative image, set alt = "" rather than omitting the attribute. alt is not a fallback image URL.
load signals that the image loaded successfully; error signals that the selected resource could not be loaded or used. These are element events, not methods or exceptions caught by wrapping the src assignment in try...catch. Attach both listeners before setting src. Alternatively, assign handlers to onload and onerror; reassignment replaces the handler in that property.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image load and error events</title>
</head>
<body>
<script>
(async () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><circle cx="5" cy="5" r="5" fill="blue"/></svg>';
const valid = 'data:image/svg+xml,' + encodeURIComponent(svg);
const invalid = 'data:image/svg+xml,not-an-svg';
function reportImage(url) {
return new Promise((resolve) => {
const img = new Image();
img.alt = 'Blue dot';
const report = (event) => {
console.log(`${event.type}: ${img.alt}`);
resolve();
};
img.addEventListener('load', report, { once: true });
img.addEventListener('error', report, { once: true });
img.src = url;
});
}
await reportImage(valid);
await reportImage(invalid);
})();
</script>
</body>
</html>Result
load: Blue dot error: Blue dot
Save the example as an HTML file, open it in a browser, and check the developer console for the output. It tests a valid SVG and then invalid image data without network requests. Both lines report the event and the unchanged `alt`; they do not demonstrate how the browser displays alternative text. A Content Security Policy that blocks `data:` images can cause the first test to fire `error` too.
Related lessons
- JavaScript · Lesson 30 · Intermediate · Version: 3