This episode is for members only

Sign up to access "Build a URL Shortener with Volt and Folio" right now.

Get started
Already a member? Sign in to continue
Playing
10. Autofocusing problems and how to fix them

Transcript

00:00
OK, so we're just going to finish up by auto focusing this input when we land on this page. Now, if we go and open up our editor and add in an auto focus to this input here and we give this a refresh, you can see it works perfectly.
00:18
That's great. However, if I were to go ahead and enter in a URL here and hit get short URL, that works nicely. We can copy it.
00:27
We can do whatever we need to do. When I click generate another short URL, you can see that it doesn't go back to auto focus. That is just because within this page, when LiveWire re-renders, the auto focus doesn't take effect.
00:41
So how are we going to get around this? Well, we've already pulled in Alpine. So what we can actually do here is when we initialize this as a component, so we can just make this a Alpine component,
00:53
we can go ahead and access the element, which is this input. And then we can call any standard JavaScript method on this. So in this case, it's going to be focus. So basically, always focus this with the auto focus.
01:07
But then once this gets re-rendered by LiveWire, we're also going to go ahead and use the manual focus when this initializes. So let's go over and take a look at the difference. Let's enter in a URL in here.
01:22
Hit get short URL. We can do whatever we need. When we click this to go back, sure enough, Alpine kicks in. It auto focuses back on.
01:30
And of course, we can go in, enter another URL into this field. So just a really small tip there, because this kind of thing can get really annoying when we're re-rendering and things like auto focus don't work.

Episode summary

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!

Episode discussion

No comments, yet. Be the first!