Skip to content

Instantly share code, notes, and snippets.

@milksense
Created June 10, 2025 16:11
Show Gist options
  • Save milksense/045d5aa4705335f4e517ade446707bab to your computer and use it in GitHub Desktop.
Save milksense/045d5aa4705335f4e517ade446707bab to your computer and use it in GitHub Desktop.
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