Created
June 10, 2025 16:11
-
-
Save milksense/045d5aa4705335f4e517ade446707bab to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { tick } from "svelte"; | |
/** | |
* Svelte action to focus an element after it is rendered. | |
* Add use:focusOnRender to HTML element to focus it after it is rendered. | |
* @param elementRef The HTML element to focus. | |
*/ | |
export function focusOnRender(elementRef: HTMLElement | null) { | |
async function update() { | |
await tick(); // Wait for the DOM to update | |
if (elementRef) { | |
// Wait another tick. | |
// This is necessary to ensure that the element is fully rendered. | |
tick().then(() => elementRef.focus()); | |
} | |
} | |
update(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment