JAVASCRIPT

Implement Focus Trapping for Keyboard Accessibility

Enhance accessibility by implementing focus trapping within a specific DOM container (e.g., a modal), ensuring keyboard users can't tab out of it.

function trapFocus(containerElement) {
    const focusableElements = containerElement.querySelectorAll(
        'a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]),'
        + 'input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]),'
        + 'input[type="checkbox"]:not([disabled]), select:not([disabled]),'
        + '[tabindex]:not([tabindex="-1"]):not([disabled])'
    );
    const firstFocusableElement = focusableElements[0];
    const lastFocusableElement = focusableElements[focusableElements.length - 1];

    if (focusableElements.length === 0) return; // No focusable elements to trap

    containerElement.addEventListener('keydown', function(e) {
        const isTabPressed = (e.key === 'Tab' || e.keyCode === 9);

        if (!isTabPressed) {
            return; // Not a Tab key press
        }

        if (e.shiftKey) { // Shift + Tab
            if (document.activeElement === firstFocusableElement) {
                lastFocusableElement.focus();
                e.preventDefault();
            }
        } else { // Tab
            if (document.activeElement === lastFocusableElement) {
                firstFocusableElement.focus();
                e.preventDefault();
            }
        }
    });

    // Set initial focus for better user experience
    firstFocusableElement.focus();
}

// Usage example:
// const myModal = document.getElementById('myAccessibleModal');
// // Call trapFocus when the modal opens
// // trapFocus(myModal);
// // Ensure to remove the keydown listener when modal closes
How it works: This `trapFocus` function improves keyboard accessibility by ensuring that when a user tabs through elements within a specified container (e.g., a modal dialog), the focus remains 'trapped' inside that container. It identifies all focusable elements within the container. When the `Tab` key (or `Shift + Tab`) is pressed, it intercepts the event and programmatically moves the focus from the last focusable element back to the first, or vice-versa, preventing the focus from escaping the container. This is crucial for WCAG compliance, particularly for modal windows and other interactive overlays, providing a seamless experience for users navigating with keyboards or assistive technologies.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs