0Pricing
Tailwind CSS Academy · Pelajaran

Modal dan Menu Tarik-Turun yang Mudah Diakses

Tambahkan aria-modal, role dialog, penjebakan fokus, dan penanganan tombol escape pada papan ketik untuk memastikan komponen pelapis sepenuhnya mudah diakses.

Modal dan Menu Tarik-Turun yang Mudah Diakses adalah pelajaran Tailwind CSS Academy gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Tailwind CSS Academy, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Tailwind CSS Academy mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Why Accessibility Is Non-Negotiable

Modals and dropdowns are among the most commonly used interactive patterns in web UIs, and they are also among the most frequently inaccessible. Users who rely on screen readers, keyboard-only navigation, or switch controls cannot use poorly implemented overlays.

Making these components accessible is not optional — it is required by WCAG 2.1 (Web Content Accessibility Guidelines) and by laws like the ADA and the EU Web Accessibility Directive. Beyond compliance, accessible components are simply better UX for everyone.

Focus Management When Modal Opens

When a modal opens, keyboard focus must move into the modal so keyboard users do not have to tab all the way through the page to reach the modal's controls. Programmatically focus the first interactive element — usually the close button or the first form field.

Store a reference to the element that triggered the modal (const trigger = document.activeElement) before opening, so you can return focus to it when the modal closes. This preserves the user's navigation position in the page.

<script>
  let triggerEl = null;

  function openModal() {
    triggerEl = document.activeElement; // save current focus position
    const modal = document.getElementById('modal');
    modal.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');

    // Move focus into the modal
    const firstFocusable = modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    if (firstFocusable) firstFocusable.focus();
  }

  function closeModal() {
    document.getElementById('modal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
    // Return focus to trigger
    if (triggerEl) triggerEl.focus();
  }
</script>

Focus Trapping Inside the Modal

While the modal is open, Tab and Shift+Tab must cycle only through the modal's interactive elements and not escape to the page behind it. This is called a focus trap.

Implement it by finding all focusable elements within the modal, detecting when the last one is focused and Tab is pressed (wrapping to the first), and detecting when the first is focused and Shift+Tab is pressed (wrapping to the last).

<script>
  function trapFocus(modalEl) {
    const focusable = modalEl.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    const firstEl = focusable[0];
    const lastEl = focusable[focusable.length - 1];

    modalEl.addEventListener('keydown', (e) => {
      if (e.key !== 'Tab') return;
      if (e.shiftKey) {
        // Shift+Tab on first element -> wrap to last
        if (document.activeElement === firstEl) {
          e.preventDefault();
          lastEl.focus();
        }
      } else {
        // Tab on last element -> wrap to first
        if (document.activeElement === lastEl) {
          e.preventDefault();
          firstEl.focus();
        }
      }
    });
  }
</script>

ARIA for Modal Dialogs

Modals require specific ARIA attributes for screen readers to understand the dialog context:

  • role='dialog' — identifies the element as a dialog
  • aria-modal='true' — tells assistive technology that content behind the dialog is inert
  • aria-labelledby — points to the dialog's visible title element
  • aria-describedby — optionally points to a description paragraph

Without these, a screen reader user opening a modal may not know they are in a dialog at all.

<div
  id="modal"
  role="dialog"
  aria-modal="true"
  aria-labelledby="modal-heading"
  aria-describedby="modal-desc"
  class="fixed inset-0 flex items-center justify-center z-50 p-4 hidden">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
    <h2 id="modal-heading" class="text-lg font-semibold text-gray-900">Confirm Action</h2>
    <p id="modal-desc" class="mt-2 text-sm text-gray-600">
      This action will permanently delete your account.
    </p>
    <div class="mt-5 flex justify-end gap-3">
      <button onclick="closeModal()" class="px-4 py-2 text-sm font-semibold border border-gray-300 rounded-lg">Cancel</button>
      <button class="px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg">Delete</button>
    </div>
  </div>
</div>

Making Background Content Inert

When a modal is open, all page content behind the backdrop should be made inert — not focusable and not interactable by screen readers. The HTML inert attribute achieves this natively, and it is now supported in all modern browsers.

Apply inert to the main content area (not the modal or backdrop) when the modal opens, and remove it when the modal closes. This provides a native alternative to complex aria-hidden attribute management.

<script>
  const mainContent = document.getElementById('main-content');

  function openModal() {
    // Make everything behind the modal inert
    mainContent.setAttribute('inert', '');
    mainContent.setAttribute('aria-hidden', 'true');

    document.getElementById('modal').classList.remove('hidden');
    document.body.classList.add('overflow-hidden');
  }

  function closeModal() {
    // Restore background content
    mainContent.removeAttribute('inert');
    mainContent.removeAttribute('aria-hidden');

    document.getElementById('modal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  }
</script>

Dropdown ARIA Roles

Accessible dropdown menus require ARIA attributes on both the trigger and the panel. The trigger button gets aria-haspopup='true' (or aria-haspopup='menu') and aria-expanded='false'. When opened, update aria-expanded to 'true'.

The dropdown panel gets role='menu', and each item inside it gets role='menuitem'. This full role set allows screen readers to announce the dropdown as a menu and navigate items with arrow keys.

<div class="relative inline-block">
  <!-- Trigger with ARIA -->
  <button
    id="dd-btn"
    aria-haspopup="menu"
    aria-expanded="false"
    aria-controls="dd-menu"
    onclick="toggleDropdown()"
    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium
           text-gray-700 bg-white border border-gray-300 rounded-lg
           hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
    Account
    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
    </svg>
  </button>
  <!-- Panel with role=menu -->
  <div
    id="dd-menu"
    role="menu"
    aria-labelledby="dd-btn"
    class="hidden absolute top-full left-0 mt-1 z-50 w-56 bg-white border border-gray-200 rounded-xl shadow-lg py-1">
    <a href="/profile" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Profile</a>
    <a href="/settings" role="menuitem" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Settings</a>
  </div>
</div>

Arrow Key Navigation in Dropdowns

WCAG requires that dropdown menu items be navigable with arrow keys: Down Arrow moves to the next item, Up Arrow moves to the previous, Home moves to the first, End moves to the last. This mirrors native OS menu behavior that keyboard users expect.

Implement this by adding a keydown listener on the menu panel that moves focus between role='menuitem' elements. Items should receive tabindex='-1' so they are programmatically focusable but not part of the Tab order.

<script>
  document.getElementById('dd-menu').addEventListener('keydown', (e) => {
    const items = [...document.querySelectorAll('[role=menuitem]')];
    const idx = items.indexOf(document.activeElement);

    if (e.key === 'ArrowDown') {
      e.preventDefault();
      items[(idx + 1) % items.length].focus();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      items[(idx - 1 + items.length) % items.length].focus();
    } else if (e.key === 'Home') {
      e.preventDefault();
      items[0].focus();
    } else if (e.key === 'End') {
      e.preventDefault();
      items[items.length - 1].focus();
    } else if (e.key === 'Escape') {
      closeDropdown();
      document.getElementById('dd-btn').focus();
    }
  });
</script>

Visible Focus Styles on All Interactive Elements

Every button, link, and interactive element inside a modal or dropdown must have a clearly visible focus indicator. Tailwind's focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-1 provides this for keyboard users without showing a ring on mouse clicks.

Remove any outline-none classes on interactive elements unless you are providing a custom focus style in its place. Invisible focus is a WCAG failure.

<!-- Close button in a modal -->
<button
  onclick="closeModal()"
  aria-label="Close dialog"
  class="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg
         focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500
         focus-visible:ring-offset-1 transition-colors">
  <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
  </svg>
</button>

Screen Reader Only Text With sr-only

Sometimes a button's visible icon is self-explanatory visually, but a screen reader needs text to announce it. Tailwind's sr-only utility visually hides text while keeping it accessible to screen readers.

Use sr-only for icon-button labels when you do not want to use aria-label, or when you want the text to be part of the DOM (useful for some screen reader behaviors). The class applies position: absolute; width: 1px; height: 1px; overflow: hidden — making it invisible but present.

<!-- Icon button with sr-only label -->
<button
  class="p-2 text-gray-500 hover:bg-gray-100 rounded-lg
         focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500">
  <svg class="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
  </svg>
  <span class="sr-only">Close modal</span>
</button>

Color Contrast in Overlays

Text inside modals and dropdown menus must meet WCAG AA contrast ratios: at least 4.5:1 for normal text and 3:1 for large text. Dark text on white backgrounds easily meets this, but subtle grays on white can fail.

The color text-gray-400 on a white background (#9ca3af on #fff) has a contrast ratio of approximately 2.5:1 — failing WCAG AA. Always use at least text-gray-500 (#6b7280, ~4.6:1) for body text in modals and text-gray-900 for primary text.

<!-- Failing contrast -->
<p class="text-gray-400">Helper text (fails WCAG AA)</p>

<!-- Passing contrast -->
<p class="text-gray-500">Helper text (passes WCAG AA ~4.6:1)</p>
<p class="text-gray-600">Body text (strong contrast ~5.9:1)</p>
<h2 class="text-gray-900">Heading (maximum contrast ~21:1)</h2>

Live Region Announcements

When dynamic content appears inside a modal or dropdown (like a loading spinner transitioning to results), a live region ensures screen readers announce the change without the user having to navigate to it. Add aria-live='polite' to a container element that will receive updates.

aria-live='polite' queues the announcement for when the user is idle. Use aria-live='assertive' only for critical errors that need immediate interruption. Overusing assertive announcements is disruptive.

<div class="p-6">
  <!-- Loading state -->
  <div id="modal-status" aria-live="polite" aria-atomic="true" class="text-center">
    <p class="text-sm text-gray-600">Loading results...</p>
  </div>
</div>

<script>
  // After data loads, update the region
  // Screen reader will announce the change
  function showResults(data) {
    document.getElementById('modal-status').innerHTML =
      '<p class="text-sm text-green-600">Found ' + data.length + ' results.</p>';
  }
</script>

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: modal accessibility requires focus management (trap focus inside, return focus on close), role='dialog' aria-modal='true', and the HTML inert attribute to lock background content; dropdown ARIA uses role='menu' on the panel, role='menuitem' on items, aria-haspopup='menu' and aria-expanded on the trigger; and Tailwind's sr-only provides screen-reader-only labels for icon-only controls. Next up we explore how the JIT engine works.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Modal dan Menu Tarik-Turun yang Mudah Diakses” gratis?

Ya — teks lengkap “Modal dan Menu Tarik-Turun yang Mudah Diakses” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Tailwind CSS Academy, upgrade ke CoddyKit PRO. Kursus Tailwind CSS Academy mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Modal dan Menu Tarik-Turun yang Mudah Diakses”?

Tambahkan aria-modal, role dialog, penjebakan fokus, dan penanganan tombol escape pada papan ketik untuk memastikan komponen pelapis sepenuhnya mudah diakses. Kamu berlatih Tailwind CSS Academy dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Tailwind CSS Academy?

Tidak diperlukan pengalaman sebelumnya. Tailwind CSS Academy di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.

Berapa lama pelajaran “Modal dan Menu Tarik-Turun yang Mudah Diakses” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Tailwind CSS Academy ini?

Ya. Setiap pelajaran Tailwind CSS Academy menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Struktur Dialog Modal
  2. Animasi Buka dan Tutup Modal
  3. Komponen Menu Tarik-Turun
  4. Modal dan Menu Tarik-Turun yang Mudah Diakses
← Kembali ke Tailwind CSS Academy