Prendendo o foco dentro do modal
Impeça que Tab escape para a página ao fundo.
Prendendo o foco dentro do modal é uma aula grátis de Web Accessibility Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web Accessibility Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web Accessibility Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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. 🎯
Perguntas Frequentes
A aula “Prendendo o foco dentro do modal” é grátis?
Sim — o texto completo de “Prendendo o foco dentro do modal” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web Accessibility Academy, atualize para CoddyKit PRO. O curso de Web Accessibility Academy inclui 4 aulas no total.
O que vou aprender em “Prendendo o foco dentro do modal”?
Impeça que Tab escape para a página ao fundo. Você pratica Web Accessibility Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web Accessibility Academy?
Nenhuma experiência prévia é necessária. Web Accessibility Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Prendendo o foco dentro do modal”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web Accessibility Academy?
Sim. Cada aula de Web Accessibility Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Papéis de diálogo e o elemento nativo dialog
- Prendendo o foco dentro do modal
- Escape para fechar e restaurar o foco
- Plano de fundo inerte e aria-modal