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
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today