Focus in input field on page load with `x-init` 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 the x-init directive in Alpine JS lets us run a JavaScript expression once the component has initiated.

We see the nuances that allow us to trigger that code before Alpine performs initial DOM updates, or after these updates have been made.

Simon Vrachliotis: [0:00] We have an input field with an x-ref attribute which allows us to trigger the focus state when a button is clicked. What we want now though is to have the input field focused immediately on page loads.

[0:12] Let's remove the button element and instead, we'll set an x-init directive on the root element of our component. x-init lets you run an expression where the component is initialized. That sounds like what we need. Inside, we'll reach for our refs object, target the nameInput ref, and call focus(). Let's reload the page and it works.

[0:36] Here's an interesting thing to note about x-init. Let's quickly set our initial name data to be Jess. In the x-init, let's console.log($refs.nameInput). We can see our input field here, but if we try to log its value with .value, it's empty. This is because x-init runs just before Alpine JS performs initial updates to the DOM.

[1:02] If we return the callback function inside of x-init, it will execute that function after the updates. You can see our console now logs Jess for the name property.

[1:13] As a recap, the x-init directive lets you run a JavaScript expression when the component is initiated, but before Alpine JS has performed initial updates to the DOM. If you pass x-init's callback function, it will wait until the initial DOM updates are made before running.

egghead
egghead
~ 20 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