Last active
May 6, 2024 21:18
-
-
Save SpenceDiNicolantonio/a8fa50a5680f0d42244c2aa72ca384c7 to your computer and use it in GitHub Desktop.
Blur on Escape directive #svelte #directive #typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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