Atrapar el foco dentro del modal
Impida que Tab escape a la página situada detrás.
Atrapar el foco dentro del modal es una lección gratuita de Web Accessibility Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web Accessibility Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web Accessibility Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Focus Must Stay In
While a modal is open, keyboard focus should stay inside it. If Tab escapes to the page behind, blind users get lost in content they cannot see.
The Native Element Helps
A real dialog opened with showModal() traps focus for you automatically, which is one big reason to prefer it over a div.
When You Build Your Own
If you roll a custom modal with a div, you must trap focus yourself, because nothing stops Tab from leaking out to the page.
Move Focus In on Open
First, send focus into the modal when it opens, usually to the first control or the heading, so the user starts in the right place.
modal.querySelector('button').focus();Find the Focusable Elements
Collect the modal's focusable items: links, buttons, inputs, and anything with tabindex. You need the first and last to build the loop.
modal.querySelectorAll('a, button, input, [tabindex]');Loop From Last to First
When Tab is pressed on the last element, send focus back to the first. This wraps the user around instead of letting them out.
if (e.key==='Tab' && !e.shiftKey && active===last){
e.preventDefault(); first.focus();
}Loop From First to Last
Handle Shift+Tab on the first element too: send focus to the last one so backward tabbing also stays trapped.
if (e.key==='Tab' && e.shiftKey && active===first){
e.preventDefault(); last.focus();
}Prevent the Default Tab
At the edges you must call preventDefault(), otherwise the browser moves focus out before your code can redirect it.
e.preventDefault();Mind Disabled and Hidden Items
Skip elements that are disabled or hidden when picking first and last, since they cannot actually receive focus.
Do Not Forget the Background
Trapping focus pairs with making the page behind inert, so even a stray click or screen reader cannot reach it while the modal is open.
Test It With the Keyboard
Tab through the whole modal and watch the focus ring cycle without ever leaving. That round trip is your proof the trap works. ✅
Quick Check
You built a custom div modal. What must you do to keep Tab inside it?
Recap: Keep Focus Captive
You learned to move focus in on open and loop it at both edges, so keyboard users stay inside the modal until they choose to close it. 🎯
Preguntas frecuentes
¿La lección «Atrapar el foco dentro del modal» es gratis?
Sí — el texto completo de «Atrapar el foco dentro del modal» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web Accessibility Academy, actualiza a CoddyKit PRO. El curso de Web Accessibility Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Atrapar el foco dentro del modal»?
Impida que Tab escape a la página situada detrás. Practicas Web Accessibility Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Web Accessibility Academy?
No se requiere experiencia previa. Web Accessibility Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Atrapar el foco dentro del modal»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Web Accessibility Academy?
Sí. Cada lección de Web Accessibility Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Roles de diálogo y el elemento nativo dialog
- Atrapar el foco dentro del modal
- Escape para cerrar y restaurar el foco
- Fondo inerte y aria-modal