Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Last active May 6, 2024 21:18
Show Gist options
  • Save SpenceDiNicolantonio/a8fa50a5680f0d42244c2aa72ca384c7 to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/a8fa50a5680f0d42244c2aa72ca384c7 to your computer and use it in GitHub Desktop.
Blur on Escape directive #svelte #directive #typescript
export interface Options {
bubble: boolean;
}
// When applied to an input, it will blur the input when the escape key is pressed
// By default it will prevent the default action of the escape key, which is useful
// for inputs in dialogs
export default function blurOnEscape(node: HTMLElement, options: Options = { bubble: false }) {
const onKeydown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
node.blur();
if (!options.bubble) {
event.preventDefault();
}
};
node.addEventListener('keydown', onKeydown);
return {
destroy: () => node.removeEventListener('keydown', onKeydown),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment