Mini-Build: Interactive Modal Popup
Build an interactive modal popup using DOM manipulation and events — open, close, click outside to dismiss, and escape key to close. This pattern is used in every web application.
Modal Features
- Open modal — Click button → show overlay + modal box
- Close modal — Click X button, click outside (overlay), or press Escape
- Prevent scroll — Lock body scroll when modal is open
- Accessibility — Focus trap inside modal, close with Escape
- Animation — Fade in/out with CSS transitions + JS class toggle
Modal Code
// Modal Popup Logic (JavaScript only)
class Modal {
constructor() {
this.isOpen = false;
this.onOpen = null;
this.onClose = null;
}
open(title, content) {
this.isOpen = true;
console.log("📦 Modal Opened");
console.log(`Title: ${title}`);
console.log(`Content: ${content}`);
// In real app:
// overlay.classList.add("active");
// modal.classList.add("active");
// document.body.style.overflow = "hidden";
if (this.onOpen) this.onOpen();
}
close() {
this.isOpen = false;
console.log("❌ Modal Closed");
// In real app:
// overlay.classList.remove("active");
// modal.classList.remove("active");
// document.body.style.overflow = "";
if (this.onClose) this.onClose();
}
toggle(title, content) {
this.isOpen ? this.close() : this.open(title, content);
}
}
// Usage
const modal = new Modal();
// Open button click
modal.open("Welcome!", "Thanks for visiting our site.");
// Close scenarios:
// 1. X button: modal.close()
// 2. Click overlay: overlay.addEventListener("click", () => modal.close())
// 3. Escape key:
// document.addEventListener("keydown", (e) => {
// if (e.key === "Escape" && modal.isOpen) modal.close();
// });
// Close the modal
modal.close();
// Open with callback
modal.onClose = () => console.log("Cleanup after modal closed!");
modal.open("Confirm", "Are you sure?");
modal.close();Tip
Tip
Always provide multiple ways to close modals: close button, clicking the overlay, pressing Escape key. This follows accessibility best practices and matches user expectations from native dialog behavior.
The DOM represents HTML as a tree of nodes that JavaScript can manipulate
Common Mistake
Warning
Not trapping focus inside the modal. When a modal is open, Tab should cycle through modal elements only, not the background page. Use focus management for accessible modals: focus first element on open, restore focus on close.
Practice Task
Note
Build an accessible modal: (1) Open on button click, close on X, overlay click, and Escape. (2) Trap focus inside the modal (Tab cycles through modal elements). (3) Animate the modal with CSS transitions on open/close.
Quick Quiz
Key Takeaways
- Build an interactive modal popup using DOM manipulation and events — open, close, click outside to dismiss, and escape key to close.
- Open modal — Click button → show overlay + modal box
- Close modal — Click X button, click outside (overlay), or press Escape
- Prevent scroll — Lock body scroll when modal is open