0Pricing
Web Accessibility Academy · Урок

Удержание фокуса внутри модального окна

Не позволяйте Tab перемещать фокус на страницу позади окна.

«Удержание фокуса внутри модального окна» — бесплатный урок Web Accessibility Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web Accessibility Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web Accessibility Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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. 🎯

Часто задаваемые вопросы

Урок «Удержание фокуса внутри модального окна» бесплатный?

Да — полный текст урока «Удержание фокуса внутри модального окна» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web Accessibility Academy, подпишись на CoddyKit PRO. Курс Web Accessibility Academy содержит 4 уроков всего.

Чему я научусь в уроке «Удержание фокуса внутри модального окна»?

Не позволяйте Tab перемещать фокус на страницу позади окна. Ты практикуешь Web Accessibility Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Web Accessibility Academy?

Предыдущий опыт не требуется. Web Accessibility Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Удержание фокуса внутри модального окна»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Web Accessibility Academy?

Да. Каждый урок Web Accessibility Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Роли диалоговых окон и встроенный элемент dialog
  2. Удержание фокуса внутри модального окна
  3. Закрытие по Escape и восстановление фокуса
  4. Неактивный фон и aria-modal
← Назад к Web Accessibility Academy