How do you implement a focus trap in a modal in JavaScript?
On Tab key, check if the active element is the first or last focusable element. If shift+Tab on the first, prevent default and focus the last. If Tab on the last, prevent default and focus the first. This keeps tab navigation inside the modal.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Build a Modal/Dialog in an Interview
Create an overlay and modal container. Open/close with a class toggle. Handle overlay click (close if clicking the overlay, not the modal), escape key, focus trap (tab stays inside), scroll lock (body overflow hidden), and restore focus to the trigger on close.
Check event.target: if (e.target === overlay) closeModal(). Clicking the modal itself does not match the overlay, so it does not close. Clicking the overlay (outside the modal) does.
Set document.body.style.overflow = 'hidden' when the modal opens. Reset to '' when it closes. This prevents the background from scrolling while the modal is open.
Still have questions?
Browse all our FAQs or reach out to our support team
