outsidePress()
Close a popover after an outside click. Dismiss on outside pointer press.
Try it
Open the filters panel, change a checkbox, then click elsewhere. Inside interactions keep it open. Escape also closes the panel and returns focus to its trigger.
Filters closed.
<div id="your-component">
<button data-open aria-expanded="false" aria-controls="filters-panel">Filter projects</button><section id="filters-panel" class="filter-popover" hidden><strong>Show projects</strong><label class="check-label"><input type="checkbox" checked> In progress</label><label class="check-label"><input type="checkbox" checked> Planned</label><label class="check-label"><input type="checkbox"> Archived</label></section><p class="demo-status" role="status">Filters closed.</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 trigger = el.querySelector('button');
const panel = el.querySelector('section');
function open(value) {
panel.hidden = !value;
trigger.setAttribute('aria-expanded', String(value));
status(value ? 'Filters open. Interact inside or click elsewhere.' : 'Filters closed.');
}
trigger.addEventListener('click', () => open(panel.hidden), { signal });
el.addEventListener('keydown', event => {
if (event.key === 'Escape' && !panel.hidden) { open(false); trigger.focus(); }
}, { signal });
return kit.outsidePress(() => [trigger, panel], () => {
if (!panel.hidden) open(false);
});
}
const stop = setup();
// Call when this component is removed.
function cleanup() {
listeners.abort();
stop?.();
}Add it to your project
- 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.
- Connect the behavior. Copy the JavaScript tab, update
#your-componentand initialize it after the elements exist. Replace simulated operations with your own data. - 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
Pass inside() returning the trigger, panel and any portalled descendants, plus dismiss(event). Dismissal occurs only when the same primary pointer starts and ends outside those elements.
- Interface
inside() array, dismiss; returns cleanup.- Lifecycle
- The returned cleanup removes captured document listeners. Re-evaluate inside elements through the callback so moved or portalled panels remain included.
Accessibility and safety
Implementation notes
Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.
Add Escape separately and let only the topmost overlay handle it. Focus return and focus containment belong to your overlay component.
What to check
Press inside and release outside: the panel should stay open. Then press and release outside to dismiss, including portalled panel content.
View documented module source
/** Typeahead for a custom menu/listbox. Pass visible enabled items only.
* Repeated letters cycle matching items; multi-letter input matches prefixes.
* Does not assign ARIA roles or selection; your widget owns those semantics. */
export function typeahead(root, { items, label = e => e.textContent.trim(), timeout = 600 } = {}) {
let buffer = '', last = 0;
function key(e) {
if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey || e.key.length !== 1 || e.key === ' ' || e.target.closest('input,textarea,[contenteditable]')) return;
const now = Date.now(), char = e.key.toLocaleLowerCase();
buffer = now - last > timeout ? char : buffer + char; last = now;
const repeated = [...buffer].every(c => c === char);
const query = repeated ? char : buffer;
const list = [...items()]; if (!list.length) return;
const index = list.indexOf(document.activeElement);
const start = repeated ? index + 1 : Math.max(0,index);
for (let n = 0; n < list.length; n++) {
const item = list[(start+n)%list.length];
if (label(item).toLocaleLowerCase().startsWith(query)) { e.preventDefault(); item.focus(); break; }
}
}
root.addEventListener('keydown', key);
return () => root.removeEventListener('keydown', key);
}
/** Dismiss an overlay when pointer starts AND ends outside it.
* Include trigger and portalled descendants in `inside()`.
* Keyboard Escape is intentionally separate: only the topmost overlay
* should handle it. Use your framework's overlay stack if available. */
export function outsidePress(inside, dismiss, doc = document) {
let outside = false, pointer = null;
const isOutside = e => !inside().some(el => e.composedPath().includes(el));
function down(e) { if (!e.isPrimary || e.button !== 0) return; pointer = e.pointerId; outside = isOutside(e); }
function up(e) { if (pointer !== e.pointerId) return; const close = outside && isOutside(e); pointer = null; outside = false; if (close) dismiss(e); }
function cancel() { pointer = null; outside = false; }
doc.addEventListener('pointerdown',down,true); doc.addEventListener('pointerup',up,true); doc.addEventListener('pointercancel',cancel,true);
return () => { doc.removeEventListener('pointerdown',down,true); doc.removeEventListener('pointerup',up,true); doc.removeEventListener('pointercancel',cancel,true); };
}
/** Save/restore list scroll position and optional filter state.
* Call restore AFTER content is rendered; key by route and list identity.
* Memory-only by default: no sensitive search terms persisted to storage. */
export function navigationMemory({ max = 30 } = {}) {
const cache = new Map();
return {
save(key, element, state = {}) { cache.delete(key); cache.set(key,{ top:element.scrollTop,left:element.scrollLeft,state:structuredClone(state) }); while(cache.size>max) cache.delete(cache.keys().next().value); },
read(key) { const value=cache.get(key); return value ? structuredClone(value.state) : null; },
restore(key,element) { const value=cache.get(key); if(value) element.scrollTo({top:value.top,left:value.left,behavior:'instant'}); return Boolean(value); },
clear() { cache.clear(); }
};
}