การสร้าง Modal ด้วย HTML และ Vanilla JavaScript ให้ผ่านเกณฑ์ WCAG 2.2 Level AA โดยไม่ต้องพึ่งไลบรารีภายนอก มีหัวใจสำคัญ 4 ข้อ:
- Focus Management: เลื่อนโฟกัสเข้าไปที่ Element แรกทันทีที่เปิด, ขังโฟกัส (Focus Trap) เมื่อกด Tab หรือ Shift+Tab และคืนโฟกัสกลับมายังปุ่มเปิดเดิมเมื่อปิด
- Keyboard Support: ปิด Modal เมื่อกดปุ่ม Esc
- Background Isolation (Inert): ใช้แอตทริบิวต์
inertบนคอนเทนเนอร์หลักของหน้าเว็บ เพื่อตัดการอ่านของ Screen Reader และป้องกันการคลิกทะลุไปฉากหลัง - ARIA Roles: กำหนด
role="dialog",aria-modal="true", พร้อมผูกaria-labelledbyและaria-describedby
โครงสร้าง HTML
SQL
<!-- เนื้อหาหลักของหน้าเว็บ (ใส่ ID ไว้เพื่อสั่ง inert) -->
<div id="app-root">
<h1>ระบบตัวอย่าง Modal Dialog</h1>
<button id="open-modal">เปิด Modal</button>
</div>
<!-- Modal Dialog -->
<div id="modal" class="modal" inert>
<div class="modal-content">
<span id="modal-title" class="modal-title">ข้อความใน Modal</span>
<p>นี่คือเนื้อหาใน Modal</p>
<button id="close-modal">ปิด Modal</button>
</div>
</div>
โค้ด JavaScript
SQL
const openModalButton = document.getElementById('open-modal');
const closeModalButton = document.getElementById('close-modal');
const modal = document.getElementById('modal');
const appRoot = document.getElementById('app-root');
openModalButton.addEventListener('click', () => {
modal.removeAttribute('inert');
modal.style.display = 'block';
closeModalButton.focus();
});
closeModalButton.addEventListener('click', () => {
modal.setAttribute('inert', '');
modal.style.display = 'none';
openModalButton.focus();
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !modal.hasAttribute('inert')) {
closeModalButton.click();
}
});
modal.addEventListener('keydown', (event) => {
if (event.key === 'Tab') {
const focusableElements = modal.querySelectorAll('button');
const firstFocusable = focusableElements[0];
const lastFocusable = focusableElements[focusableElements.length - 1];
if (document.activeElement === lastFocusable && !event.shiftKey) {
firstFocusable.focus();
event.preventDefault();
}
if (document.activeElement === firstFocusable && event.shiftKey) {
lastFocusable.focus();
event.preventDefault();
}
}
});
บทสรุป
บทความนี้ได้แสดงวิธีการสร้าง Modal Dialog ที่สามารถใช้งานได้ด้วยการใช้ HTML และ Vanilla JavaScript ตามมาตรฐาน WAI-ARIA 1.2 ซึ่งทำให้ Modal นั้นสามารถใช้งานได้สำหรับผู้ใช้ที่มีความต้องการการสนับสนุนทางการเข้าถึง เช่นผู้ใช้ที่ใช้ Screen Reader หรือผู้ใช้ที่มีปัญหาทางการเคลื่อนไหว การสร้าง Modal ด้วยวิธีนี้จะช่วยให้เว็บไซต์ของคุณมีการเข้าถึงที่ดีขึ้น และสามารถทำให้ผู้ใช้งานทุกคนสามารถใช้งานได้อย่างสะดวกสบาย