반응형
이번 24편에서는 웹 접근성을 개선하고 사용자 친화적인 경험을 제공하기 위한 유틸 함수들을 정리합니다. 키보드 네비게이션, 포커스 제어, ARIA 속성 제어 등 다양한 요소의 접근성을 손쉽게 향상시킬 수 있는 도구들입니다.
✅ 1. focusFirstElement (첫 번째 포커스 가능한 요소로 이동)
📌 주어진 컨테이너에서 포커스 가능한 첫 요소로 이동
function focusFirstElement(container) {
const focusables = container.querySelectorAll(
'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])'
);
if (focusables.length) focusables[0].focus();
}
📌 활용 예시
const modal = document.querySelector('#myModal');
focusFirstElement(modal);
✅ 2. trapFocus (포커스 순환 제한)
📌 모달 내에서만 포커스가 이동하도록 제한
function trapFocus(container) {
const focusables = container.querySelectorAll(
'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])'
);
const first = focusables[0];
const last = focusables[focusables.length - 1];
container.addEventListener('keydown', function (e) {
if (e.key !== 'Tab') return;
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
});
}
📌 활용 예시
const dialog = document.getElementById('dialog');
trapFocus(dialog);
✅ 3. setAriaExpanded (ARIA-expanded 속성 토글)
📌 버튼 등의 요소에 ARIA 속성을 동적으로 반영
function setAriaExpanded(element, expanded) {
element.setAttribute('aria-expanded', expanded);
}
📌 활용 예시
const toggle = document.querySelector('#menuToggle');
toggle.addEventListener('click', () => {
const expanded = toggle.getAttribute('aria-expanded') === 'true';
setAriaExpanded(toggle, !expanded);
});
✅ 4. announceLiveRegion (동적 텍스트 읽어주기)
📌 보조기기가 감지할 수 있도록 라이브 영역에 메시지 설정
function announceLiveRegion(message) {
const region = document.getElementById('live-region');
region.textContent = '';
setTimeout(() => {
region.textContent = message;
}, 100);
}
📌 활용 예시
<div id="live-region" role="status" aria-live="polite" style="position:absolute;overflow:hidden;width:0;height:0;"></div>
announceLiveRegion('항목이 삭제되었습니다.');
✅ 5. isFocusable (요소가 포커스 가능한지 검사)
📌 현재 요소가 포커스 가능한 상태인지 확인
function isFocusable(element) {
return element && typeof element.focus === 'function' && !element.disabled && element.tabIndex !== -1;
}
📌 활용 예시
if (isFocusable(button)) button.focus();
✅ 결론
웹 접근성은 모든 사용자가 동등하게 서비스를 이용할 수 있도록 만드는 중요한 기준입니다. 이번 유틸 함수들은 접근성 기준을 준수하면서도 개발자 생산성을 높이는 데 실질적인 도움이 됩니다.
반응형
'Programing > javascript' 카테고리의 다른 글
| 함정에 빠지기 쉬운 자바스크립트 문법4 (0) | 2025.05.05 |
|---|---|
| 함정에 빠지기 쉬운 자바스크립트 문법3 (0) | 2025.05.05 |
| 함정에 빠지기 쉬운 자바스크립트 문법2 (0) | 2025.05.05 |
| 함정에 빠지기 쉬운 자바스크립트 문법 (0) | 2025.05.05 |
| 자바스크립트 실무 유틸 함수 시리즈 23 - 브라우저 환경 감지 및 대응 유틸 (0) | 2025.05.01 |
| 자바스크립트 실무 유틸 함수 시리즈 22 - URL 및 쿼리 파라미터 처리 유틸 (0) | 2025.05.01 |
| 자바스크립트 실무 유틸 함수 시리즈 21 - 정규 표현식을 활용한 유틸 (0) | 2025.05.01 |
| 자바스크립트 실무 유틸 함수 시리즈 20 - 배열 비교 및 동기화를 위한 유틸 (0) | 2025.05.01 |