Возврат фокуса после закрытия слоя
Возвращайте пользователя туда, где он остановился.
«Возврат фокуса после закрытия слоя» — бесплатный урок Web Accessibility Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web Accessibility Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web Accessibility Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Layers Borrow Focus
When a modal, menu, or drawer opens, focus moves inside it. When it closes, you are responsible for returning focus to where the user was.
The Lost-Focus Problem
If a closed layer leaves focus on a removed element, it falls back to the page body. The user is stranded with no sense of place.
Remember the Trigger
The fix starts before opening: save a reference to the element that triggered the layer, usually document.activeElement.
const trigger = document.activeElement;Restore on Close
When the layer closes, call focus() on that saved trigger so the user lands right back where they started.
trigger.focus();The Full Round Trip
Open: store the trigger and focus the layer. Close: hide it and restore the trigger. That loop is the focus contract of any dismissible layer. 🔁
Native dialog Helps
The browser's dialog element restores focus to the opener automatically when you call close(), saving you the manual bookkeeping.
myDialog.close();Handle Every Exit Path
Restore focus no matter how the layer closes: a Close button, the Escape key, or a click on the backdrop should all return the user.
When the Trigger Is Gone
If the trigger was removed while the layer was open, send focus to a sensible nearby element instead, never to nowhere.
Why This Matters So Much
Sighted mouse users barely notice, but for keyboard and screen reader users a missed focus return can make a feature unusable.
Test It Keyboard-Only
Open the layer with Enter, close it with Escape, and confirm the focus ring reappears on the button that opened it.
Make It a Habit
Treat focus return as part of building any overlay, not an afterthought. Wire it the moment you add open and close logic.
Quick Check
A custom modal closes. What is the correct destination for focus?
Recap
You can now close the loop: save the trigger on open, restore focus to it on every close path, and lean on native dialog when you can. 🎯
Часто задаваемые вопросы
Урок «Возврат фокуса после закрытия слоя» бесплатный?
Да — полный текст урока «Возврат фокуса после закрытия слоя» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web Accessibility Academy, подпишись на CoddyKit PRO. Курс Web Accessibility Academy содержит 4 уроков всего.
Чему я научусь в уроке «Возврат фокуса после закрытия слоя»?
Возвращайте пользователя туда, где он остановился. Ты практикуешь Web Accessibility Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Web Accessibility Academy?
Предыдущий опыт не требуется. Web Accessibility Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Возврат фокуса после закрытия слоя»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Web Accessibility Academy?
Да. Каждый урок Web Accessibility Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- tabindex 0, -1 и никогда не положительный
- Перемещение фокуса после действия
- Возврат фокуса после закрытия слоя
- Управление перемещаемым tabindex в виджетах