Closed henrikvilhelmberglund closed 4 months ago
If you add this, you can find out what is stealing away focus from the button after it gets it:
document.querySelector("button").addEventListener('blur', () => {
debugger
})
As you can see, it's SvelteKit trying to restore the focus. So in this case, the best advice is to instead handle the focus inside a microtask so your logic can happen after SvelteKit:
queueMicrotask(() => {
document.querySelector("button").focus();
})
Hope that helps!
Describe the bug
I have an $effect() in a button component that focuses the first button in a div using a query selector. It works with SSR enabled but with SSR disabled the button isn't focused on initial load, but focuses when HMR kicks in when editing a file.
It also works when adding a 0 ms timeout in the $effect().
I could be doing something stupid but it could also be a bug.
Reproduction
https://stackblitz.com/github/henrikvilhelmberglund/svelte5-focus-bug?file=src%2Froutes%2F%2Bpage.js,src%2Fcomponents%2FMyButton.svelte,src%2Froutes%2F%2Bpage.svelte
Logs
No response
System Info
Severity
annoyance