Focus in input field on page load with `x-init` in Alpine JS

Share this video with your friends

Social Share Links

Send Tweet

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.