An image gallery is a small project with an outsized payoff: it teaches you rendering from data, event delegation, and modals — three patterns you will reuse in almost every app you build. Here is a complete version.
The plan
- An array of images (source, title, category).
- A grid rendered from that array — never hard-coded HTML.
- Filter buttons that show only one category.
- Click an image to open it big in a lightbox, with a close button and Escape to exit.
The HTML
<div id="filters">
<button data-filter="all">All</button>
<button data-filter="nature">Nature</button>
<button data-filter="city">City</button>
</div>
<div id="gallery"></div>
<div id="lightbox" hidden>
<img id="big" src="" alt="">
<button id="close">✕ Close</button>
</div>
The JavaScript
const images = [
{ src: 'mountain.jpg', title: 'Mountain', cat: 'nature' },
{ src: 'river.jpg', title: 'River', cat: 'nature' },
{ src: 'street.jpg', title: 'Street', cat: 'city' },
{ src: 'skyline.jpg', title: 'Skyline', cat: 'city' }
];
const gallery = document.getElementById('gallery');
function render(filter = 'all') {
const shown = images.filter(i => filter === 'all' || i.cat === filter);
gallery.innerHTML = shown.map(i => `
<figure data-src="${i.src}">
<img src="${i.src}" alt="${i.title}">
<figcaption>${i.title}</figcaption>
</figure>
`).join('');
}
// One listener on the parent handles every image (event delegation)
gallery.addEventListener('click', (e) => {
const fig = e.target.closest('figure');
if (!fig) return;
document.getElementById('big').src = fig.dataset.src;
document.getElementById('lightbox').hidden = false;
});
document.getElementById('close').addEventListener('click', () => {
document.getElementById('lightbox').hidden = true;
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
document.getElementById('lightbox').hidden = true;
}
});
document.getElementById('filters').addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') render(e.target.dataset.filter);
});
render();
Three details beginners miss
- Render from data, not from HTML. When the images live in an array, adding a photo means adding one line — not editing the page.
-
Event delegation. One listener on
#galleryhandles every image, including ones added later. Ten listeners, one per image, is how slow pages are born. - The lightbox is just a hidden div. There is no special lightbox technology. Show it, hide it, and handle Escape. That is the whole trick.
What to add next
Lazy loading with loading="lazy" on the images, a search box that filters by title, and keyboard arrows to move between photos inside the lightbox.
Top comments (0)