Skip to content

Instantly share code, notes, and snippets.

@wuhhh
Last active March 9, 2024 21:52
Show Gist options
  • Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.
Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.

Revisions

  1. Huw Roberts revised this gist Mar 9, 2024. No changes.
  2. Huw Roberts revised this gist Mar 9, 2024. 1 changed file with 8 additions and 1 deletion.
    9 changes: 8 additions & 1 deletion trap-focus.js
    Original file line number Diff line number Diff line change
    @@ -27,5 +27,12 @@ export function trapFocus(node) {

    focusable()[0]?.focus();

    // TODO finish writing the action
    node.addEventListener('keydown', handleKeydown);

    return {
    destroy() {
    node.removeEventListener('keydown', handleKeydown);
    previous?.focus();
    }
    };
    }
  3. Huw Roberts created this gist Mar 9, 2024.
    31 changes: 31 additions & 0 deletions trap-focus.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    export function trapFocus(node) {
    const previous = document.activeElement;

    function focusable() {
    return Array.from(node.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'));
    }

    function handleKeydown(event) {
    if (event.key !== 'Tab') return;

    const current = document.activeElement;

    const elements = focusable();
    const first = elements.at(0);
    const last = elements.at(-1)

    if (event.shiftKey && current === first) {
    last.focus();
    event.preventDefault();
    }

    if (!event.shiftKey && current === last) {
    first.focus();
    event.preventDefault();
    }
    }

    focusable()[0]?.focus();

    // TODO finish writing the action
    }