Subtlyv0.1.1
Keyboard & motion

captureFocus()

Return focus to the dialog opener. Restore focus after dialogs.

Available in v0.1.1focus.jsAccessibility

Try it

Open the project settings dialog and close it with its button or Escape. Notice the focus ring returning to the control that opened it.

Live example
Project settingsWebsite redesign

Open the dialog using the keyboard to follow the focus ring.

Project settings

This native dialog manages its own modal focus.

Ready. Focus will return to the opener.

<div id="your-component">
<div class="data-preview"><span class="muted">Project settings</span><strong>Website redesign</strong><p>Open the dialog using the keyboard to follow the focus ring.</p></div><button data-open>Open project settings</button><dialog class="demo-dialog" aria-labelledby="project-settings-title"><h3 id="project-settings-title">Project settings</h3><p>This native dialog manages its own modal focus.</p><label>Display name<input value="Website redesign"></label><button data-close>Close settings</button></dialog><p class="demo-status" role="status">Ready. Focus will return to the opener.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const dialog = el.querySelector('dialog');
          let restore;
          el.querySelector('[data-open]').addEventListener('click', () => {
            restore = kit.captureFocus();
            dialog.showModal();
          }, { signal });
          el.querySelector('[data-close]').addEventListener('click', () => dialog.close(), { signal });
          dialog.addEventListener('close', () => {
            restore?.(); status('Dialog closed. Focus returned to Open project settings.');
          }, { signal });
          return () => { if (dialog.open) dialog.close(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Call captureFocus() immediately before opening a dialog. It remembers the currently focused element and returns a restore function; it does not move focus into the dialog or trap it.

Interface
returns restore callback.
Lifecycle
Call the returned function after the dialog closes. It restores focus only when the original element is still connected to the document.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

Use a native dialog or an accessible modal for focus containment. Avoid adding a second focus trap to a component that already manages focus.

What to check

Open using the keyboard, close with the dialog's control, and confirm focus returns to the opener. Also test closing after the opener has been removed.

View documented module source
/** Focus restoration and roving tabindex for custom composite widgets.
 * Do not add a second focus trap to an existing accessible modal. */
export function captureFocus(){const previous=document.activeElement;return ()=>{if(previous instanceof HTMLElement&&previous.isConnected)previous.focus({preventScroll:true});};}
export function rovingFocus(root,{selector='[data-roving-item]',orientation='vertical',wrap=true}={}){
    const items=()=>[...root.querySelectorAll(selector)].filter(e=>!e.matches(':disabled,[aria-disabled="true"]')&&e.getClientRects().length);
    const originals=new Map();
    function sync(active){for(const e of items()){if(!originals.has(e))originals.set(e,e.getAttribute('tabindex'));e.tabIndex=e===active?0:-1;}}
    function refresh(){const list=items();sync(list.find(e=>e===document.activeElement)||list.find(e=>e.tabIndex===0)||list[0]);}
    function key(e){const list=items(),i=list.indexOf(e.target);if(i<0||e.altKey||e.ctrlKey||e.metaKey||!list.length)return;let n=i;const rtl=getComputedStyle(root).direction==='rtl';if(e.key==='Home')n=0;else if(e.key==='End')n=list.length-1;else if(e.key===(orientation==='vertical'?'ArrowDown':rtl?'ArrowLeft':'ArrowRight'))n++;else if(e.key===(orientation==='vertical'?'ArrowUp':rtl?'ArrowRight':'ArrowLeft'))n--;else return;e.preventDefault();n=wrap?(n+list.length)%list.length:Math.max(0,Math.min(list.length-1,n));sync(list[n]);list[n].focus();}
    function focus(e){if(items().includes(e.target))sync(e.target);}
    root.addEventListener('keydown',key);root.addEventListener('focusin',focus);refresh();
    return {refresh,destroy(){root.removeEventListener('keydown',key);root.removeEventListener('focusin',focus);for(const [e,v] of originals)v===null?e.removeAttribute('tabindex'):e.setAttribute('tabindex',v);}};
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close