In this episode, we tackle a common annoyance when working with forms: getting the input field to autofocus correctly, especially after re-rendering with tools like Livewire.
We kick things off by adding the usual autofocus
attribute to our input, and at first, it seems to work just fine when we load the page. But... as soon as we use the "generate another short URL" button, which causes a Livewire re-render, the autofocus stops working. This is because Livewire refreshes the DOM, and the autofocus
attribute doesn't reapplies automatically.
To fix this, we take advantage of Alpine's reactivity. We convert our input into an Alpine component and use a bit of JavaScript magic: as soon as the input initializes, we manually call the focus()
method on it. This ensures the field gets focus both on first load and every time Livewire re-renders the component.
By the end, you'll know exactly how to keep your input field focused, no matter how many times Livewire updates your UI. It's a small tip, but one that can save you and your users a lot of frustration!