Skip to content

Bit #29

Code snippets: Svelte action that redirect focus to element when a character key is pressed.

function keyRedirect(node: HTMLElement) {
function handleKeydown(e: KeyboardEvent) {
if (node === document.activeElement) {
return;
}
if (e.code.match(/\w/g)) {
node.focus();
}
}
window.addEventListener("keydown", handleKeydown);
return {
destroy() {
window.removeEventListener("keydown", handleKeydown);
},
};
}