Subtlyv0.1.1
Keyboard & motion

rovingFocus()

Move through a toolbar with arrow keys. Composite widget keyboard navigation.

Available in v0.1.1focus.jsAccessibility

Try it

Tab into the text alignment toolbar once, then use Left, Right, Home or End to move between controls. Activate a button to update the sample text.

Live example

Small details make a familiar interface feel easier to use.

Left alignment. Tab into the toolbar to begin.

<div id="your-component">
<div class="demo-toolbar" role="toolbar" aria-label="Text alignment" data-ix="roving-focus" data-ix-orientation="horizontal"><button data-align="left" data-ix-roving-item aria-pressed="true">Left</button><button data-align="center" data-ix-roving-item aria-pressed="false">Center</button><button data-align="right" data-ix-roving-item aria-pressed="false">Right</button></div><p class="sample-document" data-document>Small details make a familiar interface feel easier to use.</p><p class="demo-status" role="status">Left alignment. Tab into the toolbar to begin.</p>
</div>
import * as kit from 'subtly';
// Start once at application level.
const interactions = kit.createInteractions();
interactions.start();

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 buttons = [...el.querySelectorAll('[data-align]')];
          for (const button of buttons) button.addEventListener('click', () => {
            for (const item of buttons) item.setAttribute('aria-pressed', String(item === button));
            el.querySelector('[data-document]').style.textAlign = button.dataset.align;
            status(button.textContent + ' alignment selected.');
          }, { signal });
          // data-ix="roving-focus" is initialized by createInteractions().
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
  interactions.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

Attach to a composite widget with a matching item selector, orientation and wrapping behavior. One enabled visible item receives tabindex=0; arrow keys, Home and End move between items. Disabled items are skipped.

Interface
selector, orientation, wrap; refresh after DOM changes, destroy.
Lifecycle
Call refresh() after items change. destroy() removes listeners and restores the original tabindex values for the tracked items.

Accessibility and safety

Implementation notes

Use only for composite widgets with the appropriate arrow-key interaction model, not regular links or forms.

Use for widgets such as toolbars that follow an arrow-key interaction model. Do not apply it to normal page navigation or form fields; your component still owns ARIA roles.

What to check

Tab into and out of the widget, then test arrows, Home, End, disabled items and right-to-left layout. Confirm one normal Tab stop remains.

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