Focus an input with Alpine.js

To focus an input element with Alpine.js, we can use the standalone x-init directive.

<input x-init="$el.focus()" autofocus type="number">


However, if your input element is hidden and becomes visible after an event(e.g: click, change, ..) you'll need to use Alpine's $nextTick function.

    addNew: false,
    focus: function() {
        const textInput = this.$refs.myFocusedInputInput;

  <div x-show="!addNew">
    <strong x-on:click="addNew = !addNew; $nextTick(() => focus())">Add New</strong>

  <div x-show="addNew" x-cloak>
    <input type="number" x-ref="myFocusedInputInput">


********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************