Handling images
Handling images with JavaScript means using the DOM to find, create, swap and monitor <img> elements while the page is running. Common tasks include building an image gallery where clicking a thumbnail changes the main picture, preloading images so they appear instantly, showing a fallback when an image fails to load, and reading an image's real dimensions. All of it works through properties and events on image elements.
Finding and changing images
Images are ordinary elements, so querySelector works. The document also keeps a ready-made collection of every image in document.images. The most useful properties are:
src: the image address. Setting it loads a new picture.alt: the text description. Update it whenever you changesrc, so screen reader users hear the right description.widthandheight: the displayed size.naturalWidthandnaturalHeight: the file's real pixel size, available after loading.complete:trueonce the browser has finished trying to load it.
Reading img.src always returns a full absolute URL, even if the HTML said photos/a.jpg. Use img.getAttribute('src') when you need the exact value written in the markup.
A thumbnail gallery with a fallback
<img id="main-photo" src="img/beach-large.jpg" alt="Beach at sunset">
<div id="thumbs">
<img src="img/beach-thumb.jpg" data-large="img/beach-large.jpg" alt="Beach at sunset">
<img src="img/hill-thumb.jpg" data-large="img/hill-large.jpg" alt="Misty hills">
<img src="img/city-thumb.jpg" data-large="img/city-large.jpg" alt="City at night">
</div>
const main = document.querySelector('#main-photo');
const thumbs = document.querySelector('#thumbs');
// Preload the large versions so swapping feels instant
thumbs.querySelectorAll('img').forEach((t) => {
const pre = new Image();
pre.src = t.dataset.large;
});
// One listener for all thumbnails (event delegation)
thumbs.addEventListener('click', (e) => {
const thumb = e.target.closest('img');
if (!thumb) return;
main.src = thumb.dataset.large;
main.alt = thumb.alt;
});
// Show a placeholder if the image cannot be loaded
main.addEventListener('error', () => {
main.src = 'img/placeholder.png';
main.alt = 'Image not available';
}, { once: true });
main.addEventListener('load', () => {
console.log(`Loaded ${main.naturalWidth} x ${main.naturalHeight}`);
});
Load and error events
Images load in the background. The load event fires when the picture is ready, and error fires when the file is missing or broken. Listening for error lets you swap in a placeholder instead of showing a broken-image icon. The { once: true } option matters: if the placeholder itself were missing, it would trigger error again and loop forever.
new Image() creates an image element that is not on the page. Setting its src starts the download, and the browser caches the file, so when the visible image later uses the same URL it appears without delay. For modern code, await img.decode() returns a promise that resolves once the image is decoded and safe to insert without a flash.
Do not read sizes too early
A very common bug is checking naturalWidth immediately after setting src. At that moment the browser has only started downloading, so the value is 0. Wait for the load event, or check img.complete first for images that may already be cached. Also, if you attach the load listener after setting src on a cached image, the event may have already fired. Attach listeners before changing src.
For long pages, the HTML attribute loading="lazy" lets the browser delay off-screen images until the user scrolls near them, with no JavaScript required. Pair it with width and height attributes so the page reserves space and does not jump when the images arrive.
Takeaway
Change pictures by setting src and alt together, preload with new Image(), react to load and error, and only read dimensions after loading finishes.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.