Focus an input field on button click with `x-ref` and the `$refs` property in Alpine JS

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we learn how to retrieve a DOM element via the x-ref directive in Alpine JS, which gives us a reference to the element it is applied on. In our case, an input field.

We can then use the $refs object, and reach for the ref we need to target.

This allows us to trigger the focus state of the input field, with the .focus() method.

Instructor: [0:00] Here's a simple app where a user can type their name in an input field and the text below will update to display the name entered. We also have a button here. When we click it, we want the input fields to become in focus.

[0:13] We can add an add-click directive to the button, but how do we make our input field focus? This is where the X ref directive comes handy. X ref allows us to retrieve a row DOM element and make it available inside a $refs object which can be used in the on-click event handler.

[0:32] We'll call our ref name input here. Down in our buttons click event handler, we can reach for $refs.name input and call .focus on it. Now, when we click the button, the input field gets in focus.

[0:50] To recap, we can use the XREF directive to attach a reference to the DOM element which can then be accessed through the $refSObject. With this in place, we can reach for $Refs.name input and call the focus() method on it.