Project: Image Gallery App
Build a polished, fully interactive Image Gallery with a lightbox overlay, category filters, keyboard navigation (← → Esc), smooth CSS transitions, and lazy loading — all with zero frameworks, pure vanilla JavaScript.
Project Overview
The Image Gallery is a classic frontend project that exercises your DOM skills, event handling, CSS transitions, and browser APIs in a visually rich context. It mirrors how real-world galleries work on portfolio sites, e-commerce product pages, and photography platforms.
You'll store image data in a JavaScript array of objects, render the grid dynamically, and layer a lightbox on top — a modal that shows the full-size image with navigation controls. Category filter buttons will hide/show images with a smooth CSS animation, and IntersectionObserver will handle lazy loading so images only download when they scroll into view.
Features We'll Build
Every feature maps directly to a JavaScript concept covered earlier in this course.
Concepts used in this project:
Project Folder Structure
Three files, one folder — the cleanest possible setup for a pure JS project:
Step 1 — HTML Structure
The HTML is deliberately minimal — we render all gallery cards via JavaScript. The static HTML only provides the filter bar, the empty grid container, and the lightbox shell (which JS will populate on demand).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Gallery</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<header class="gallery-header">
<h1>🖼️ Image Gallery</h1>
<p class="gallery-sub">Click any image to open the lightbox</p>
</header>
<!-- Filter Bar -->
<div class="filter-bar" id="filterBar">
<!-- Buttons injected by JS -->
</div>
<!-- Image Grid -->
<div class="gallery-grid" id="galleryGrid"></div>
</div>
<!-- Lightbox Overlay -->
<div class="lightbox" id="lightbox" role="dialog" aria-modal="true">
<div class="lb-backdrop" id="lbBackdrop"></div>
<div class="lb-panel">
<button class="lb-btn lb-close" id="lbClose" aria-label="Close">✕</button>
<button class="lb-btn lb-prev" id="lbPrev" aria-label="Previous">←</button>
<button class="lb-btn lb-next" id="lbNext" aria-label="Next">→</button>
<img class="lb-img" id="lbImg" src="" alt="" />
<div class="lb-footer">
<span class="lb-caption" id="lbCaption"></span>
<span class="lb-counter" id="lbCounter"></span>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
role="dialog" and aria-modal="true"
attributes on the lightbox are ARIA accessibility attributes. They tell
screen readers that this element behaves as a modal dialog — a good habit in every real project.
Step 2 — CSS Styling
The CSS handles three distinct areas: the responsive grid,
the lightbox overlay (positioned fixed over the whole viewport), and the
filter bar with active button state. Notice how opacity
+ transform animate the hidden images — this is far
smoother than toggling display:none.
/* ── Variables ──────────────────────────────────── */
:root {
--bg: #0f172a;
--card-bg: #1e293b;
--border: rgba(255,255,255,.08);
--text: #f1f5f9;
--text-muted: #94a3b8;
--accent: #f7df1e;
--radius: 12px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
padding: 32px 16px;
}
.container { max-width: 960px; margin: 0 auto; }
/* ── Header ─────────────────────────────────────── */
.gallery-header { margin-bottom: 28px; }
.gallery-header h1 { font-size: 28px; font-weight: 700; color: var(--accent); }
.gallery-sub { font-size: 14px; color: var(--text-muted); margin-top: 4px; }
/* ── Filter Bar ─────────────────────────────────── */
.filter-bar {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 24px;
}
.filter-btn {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 20px;
padding: 7px 18px;
font-size: 13px;
color: var(--text-muted);
cursor: pointer;
transition: all .2s;
}
.filter-btn:hover { border-color: rgba(247,223,30,.4); color: var(--text); }
.filter-btn.active {
background: var(--accent);
color: #1a1a14;
border-color: var(--accent);
font-weight: 600;
}
/* ── Gallery Grid ───────────────────────────────── */
.gallery-grid {
columns: 3 240px;
gap: 14px;
}
.gallery-item {
break-inside: avoid;
margin-bottom: 14px;
border-radius: var(--radius);
overflow: hidden;
cursor: pointer;
position: relative;
opacity: 1;
transform: scale(1);
transition: opacity .35s ease, transform .35s ease;
}
.gallery-item.hidden {
opacity: 0;
transform: scale(0.95);
pointer-events: none;
position: absolute;
visibility: hidden;
}
.gallery-item img {
width: 100%;
height: auto;
display: block;
transition: transform .3s ease;
}
.gallery-item:hover img { transform: scale(1.04); }
.gallery-item .overlay {
position: absolute;
inset: 0;
background: linear-gradient(to top, rgba(0,0,0,.7) 0%, transparent 50%);
opacity: 0;
transition: opacity .3s;
display: flex;
align-items: flex-end;
padding: 14px;
}
.gallery-item:hover .overlay { opacity: 1; }
.overlay-caption {
font-size: 13px;
font-weight: 500;
color: #fff;
}
/* Lazy load placeholder */
.gallery-item img[data-src] {
background: var(--card-bg);
min-height: 180px;
}
/* ── Lightbox ───────────────────────────────────── */
.lightbox {
position: fixed;
inset: 0;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
pointer-events: none;
transition: opacity .25s ease;
}
.lightbox.open { opacity: 1; pointer-events: all; }
.lb-backdrop {
position: absolute;
inset: 0;
background: rgba(0,0,0,.88);
backdrop-filter: blur(6px);
}
.lb-panel {
position: relative;
z-index: 1;
max-width: 90vw;
max-height: 90vh;
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.lb-img {
max-width: 85vw;
max-height: 78vh;
border-radius: 14px;
object-fit: contain;
box-shadow: 0 20px 80px rgba(0,0,0,.6);
transition: opacity .2s;
}
.lb-footer {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 4px;
}
.lb-caption { font-size: 14px; color: rgba(255,255,255,.8); }
.lb-counter { font-size: 13px; color: rgba(255,255,255,.5); font-family: monospace; }
.lb-btn {
position: absolute;
background: rgba(255,255,255,.1);
backdrop-filter: blur(8px);
border: 1px solid rgba(255,255,255,.15);
color: #fff;
border-radius: 50%;
width: 42px;
height: 42px;
cursor: pointer;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
transition: background .2s;
}
.lb-btn:hover { background: rgba(247,223,30,.25); }
.lb-close { top: -52px; right: 0; }
.lb-prev { left: -56px; top: 50%; transform: translateY(-50%); }
.lb-next { right: -56px; top: 50%; transform: translateY(-50%); }
/* Body scroll lock */
body.lb-open { overflow: hidden; }
/* ── Responsive ─────────────────────────────────── */
@media (max-width: 600px) {
.gallery-grid { columns: 2 140px; }
.lb-prev { left: -44px; }
.lb-next { right: -44px; }
}
columns creates a natural masonry
layout
where images flow into columns of equal width. Unlike CSS Grid, images of different heights pack
tightly without gaps — perfect for a photography gallery.
Step 3 — JavaScript Logic
All logic lives in app.js, split into
clean, focused functions. We start with the image data array, then build out
rendering, filtering, the lightbox, keyboard navigation, and lazy loading.
id, src, caption, and category. All rendering derives from this single
source of truth.data-src instead of src on images to defer loading until
IntersectionObserver fires.hidden class
on items that don't match the selected category. The CSS transition handles the
visual animation.navigate(1) or navigate(-1) cycles through visible images,
wrapping at both ends.keydown listener
handles Esc / ← /→. IntersectionObserver swaps data-src → src when an image enters the viewport
for the first time./* ── 1. IMAGE DATA ────────────────────────────────────────── */
const images = [
{ id:1, src:'https://picsum.photos/seed/arch1/600/800', caption:'City Skyline', category:'architecture' },
{ id:2, src:'https://picsum.photos/seed/nat1/800/600', caption:'Mountain Lake', category:'nature' },
{ id:3, src:'https://picsum.photos/seed/ppl1/600/700', caption:'Street Portrait', category:'people' },
{ id:4, src:'https://picsum.photos/seed/arch2/700/500', caption:'Glass Tower', category:'architecture' },
{ id:5, src:'https://picsum.photos/seed/nat2/600/900', caption:'Forest Path', category:'nature' },
{ id:6, src:'https://picsum.photos/seed/abst1/800/600', caption:'Colour Splash', category:'abstract' },
{ id:7, src:'https://picsum.photos/seed/ppl2/600/800', caption:'Golden Hour', category:'people' },
{ id:8, src:'https://picsum.photos/seed/arch3/700/600', caption:'Old Doorway', category:'architecture' },
{ id:9, src:'https://picsum.photos/seed/nat3/800/700', caption:'Ocean Waves', category:'nature' },
{ id:10, src:'https://picsum.photos/seed/abst2/600/600', caption:'Neon Lights', category:'abstract' },
{ id:11, src:'https://picsum.photos/seed/ppl3/700/900', caption:'Candid Moment', category:'people' },
{ id:12, src:'https://picsum.photos/seed/nat4/600/800', caption:'Desert Dunes', category:'nature' },
];
/* ── 2. STATE ─────────────────────────────────────────────── */
let activeFilter = 'all';
let currentIndex = 0; // index within visibleImages()
function visibleImages() {
return activeFilter === 'all'
? images
: images.filter(img => img.category === activeFilter);
}
/* ── 3. DOM REFS ──────────────────────────────────────────── */
const grid = document.getElementById('galleryGrid');
const filterBar = document.getElementById('filterBar');
const lightbox = document.getElementById('lightbox');
const lbImg = document.getElementById('lbImg');
const lbCaption = document.getElementById('lbCaption');
const lbCounter = document.getElementById('lbCounter');
/* ── 4. BUILD FILTER BUTTONS ──────────────────────────────── */
function buildFilters() {
const cats = ['all', ...new Set(images.map(i => i.category))];
filterBar.innerHTML = cats.map(c => `
<button class="filter-btn${c === activeFilter ? ' active' : ''}"
data-cat="${c}">
${c.charAt(0).toUpperCase() + c.slice(1)}
</button>
`).join('');
}
/* ── 5. RENDER GALLERY CARDS ──────────────────────────────── */
function renderGallery() {
grid.innerHTML = images.map((img, idx) => `
<div class="gallery-item"
data-id="${img.id}"
data-idx="${idx}"
data-cat="${img.category}">
<img data-src="${img.src}"
alt="${img.caption}"
width="600" height="400" />
<div class="overlay">
<span class="overlay-caption">${img.caption}</span>
</div>
</div>
`).join('');
applyFilter();
initLazyLoad();
}
/* ── 6. APPLY FILTER (toggle hidden class) ────────────────── */
function applyFilter() {
document.querySelectorAll('.gallery-item').forEach(item => {
const match = activeFilter === 'all' || item.dataset.cat === activeFilter;
item.classList.toggle('hidden', !match);
});
}
/* ── 7. LAZY LOAD (IntersectionObserver) ──────────────────── */
function initLazyLoad() {
const obs = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
delete img.dataset.src;
observer.unobserve(img);
}
});
}, { rootMargin: '0px 0px 200px 0px' });
document.querySelectorAll('img[data-src]').forEach(img => obs.observe(img));
}
/* ── 8. LIGHTBOX — OPEN ───────────────────────────────────── */
function openLightbox(idx) {
const visible = visibleImages();
if (!visible.length) return;
currentIndex = idx;
const img = visible[currentIndex];
lbImg.src = img.src;
lbImg.alt = img.caption;
lbCaption.textContent = img.caption;
lbCounter.textContent = `${currentIndex + 1} / ${visible.length}`;
lightbox.classList.add('open');
document.body.classList.add('lb-open');
}
/* ── 9. LIGHTBOX — CLOSE ──────────────────────────────────── */
function closeLightbox() {
lightbox.classList.remove('open');
document.body.classList.remove('lb-open');
lbImg.src = '';
}
/* ── 10. LIGHTBOX — NAVIGATE ──────────────────────────────── */
function navigate(dir) {
const visible = visibleImages();
currentIndex = (currentIndex + dir + visible.length) % visible.length;
openLightbox(currentIndex);
}
/* ── 11. EVENTS ───────────────────────────────────────────── */
// Filter bar clicks (event delegation)
filterBar.addEventListener('click', e => {
const btn = e.target.closest('.filter-btn');
if (!btn) return;
activeFilter = btn.dataset.cat;
document.querySelectorAll('.filter-btn').forEach(b =>
b.classList.toggle('active', b === btn));
applyFilter();
});
// Gallery grid clicks (event delegation)
grid.addEventListener('click', e => {
const item = e.target.closest('.gallery-item');
if (!item || item.classList.contains('hidden')) return;
const visible = visibleImages();
const imgId = parseInt(item.dataset.id);
const idx = visible.findIndex(i => i.id === imgId);
if (idx !== -1) openLightbox(idx);
});
// Lightbox controls
document.getElementById('lbClose').addEventListener('click', closeLightbox);
document.getElementById('lbPrev').addEventListener('click', () => navigate(-1));
document.getElementById('lbNext').addEventListener('click', () => navigate(1));
document.getElementById('lbBackdrop').addEventListener('click', closeLightbox);
// Keyboard navigation
document.addEventListener('keydown', e => {
if (!lightbox.classList.contains('open')) return;
if (e.key === 'ArrowLeft') navigate(-1);
if (e.key === 'ArrowRight') navigate(1);
if (e.key === 'Escape') closeLightbox();
});
/* ── 12. INIT ─────────────────────────────────────────────── */
buildFilters();
renderGallery();
Keyboard Shortcuts
Adding keyboard support makes your gallery feel professional and is
accessible to users who can't use a mouse. All three shortcuts are handled by a single
keydown listener.
if (!lightbox.classList.contains('open')) return;
— this ensures keys only fire when the lightbox is actually open, preventing conflicts with
other page interactions.
How It All Connects
Every feature maps to a specific JavaScript concept you covered earlier in the course:
| App Feature | JS Concept Used | Chapter Reference |
|---|---|---|
| Image data source | Array of objects | Ch 35 — Objects Basics |
| Render grid cards | Array.map + innerHTML + template literals | Ch 32 — map, Ch 42 — DOM Manipulation |
| Filter by category | classList.toggle('hidden') + Array.filter | Ch 32 — filter, Ch 42 — DOM Manipulation |
| Filter button clicks | Event delegation on parent container | Ch 44 — Event Delegation |
| Open lightbox | classList.add + data-* attributes | Ch 40 — DOM Introduction |
| Navigate prev/next | Modulo arithmetic on array index | Ch 13 — Operators Overview |
| Keyboard shortcuts | document.addEventListener('keydown') | Ch 43 — Events & Listeners |
| Lazy loading | IntersectionObserver API | Web APIs (browser built-in) |
| Body scroll lock | document.body.classList.add | Ch 42 — Manipulating the DOM |
Key Concepts Deep Dive
data-src → src only when the image is about to be
seen, saving bandwidth.columns property fills
elements into vertical columns left-to-right, creating a Pinterest-style layout where
images of different heights pack naturally without gaps.(index + dir + length) % length keeps the index within
bounds while wrapping: going "next" on the last image returns to index 0, and "prev" on
index 0 wraps to the last.body { overflow: hidden } prevents the background page
from scrolling. Removing the class on close restores normal scroll — a pattern used on
every modal on the web.e.target.closest('.gallery-item') to find the clicked
card. Scales to any number of images.display:none
for filtering — it can't animate. Instead we toggle opacity + transform + visibility via a .hidden class so items fade out smoothly.Common Mistakes to Avoid
display. Always use opacity + visibility + pointer-events together for smooth animated show/hide.
src immediately, the browser downloads all 12 images
at once. Use data-src and copy it to src only when IntersectionObserver fires.visibleImages() inside
navigate() — never cache the visible list — so it
stays in sync with the active filter.
Try It Yourself
The live editor below has the complete single-file Image Gallery. Click any image thumbnail to open the lightbox. Use the arrow buttons or keyboard ← → keys to navigate, and Esc or the ✕ button to close.
<a download> trick, (3) implement a
touch swipe gesture using touchstart / touchend
events for mobile lightbox navigation.
What does IntersectionObserver do in the Image Gallery project?
- The Image Gallery project combines DOM rendering, event delegation, CSS transitions, and browser APIs in a visually rich real-world app.
- Store all image data in a JavaScript array of objects — rendering derives from this single source of truth.
- Use CSS columns for a masonry layout and
opacity + transform(neverdisplay:none) for animated filtering. - The lightbox uses
position:fixedand body scroll lock to overlay the full viewport cleanly. - Modulo arithmetic
(index + dir + length) % lengthwraps navigation at both ends without an if-else chain. - A single keydown listener guards all keyboard shortcuts — always check that the lightbox is open before acting.
- IntersectionObserver defers image downloads until they enter the viewport, cutting initial page load time significantly.
- Possible extensions: search/text filter, touch swipe support, download button, zoom on click, image counter progress bar.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.