點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-init to Set Focus

Sam Xiao's Avatar 2022-02-12

Alpine’s x-init is just like Vue’s mounted hook. We can run some expressions in x-init.

Version

Alpine 3.8

x-init

focus000

The textbox is focused on page loads.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body>
    <input x-data x-init="$el.focus()" />
  </body>
</html>

Line 10

<input x-data x-init="$el.focus()" />
  • x-data : make the current element as a single-element component
  • x-init : run expressions on initialization phase of the component
  • $el : retrieve the current DOM element

Conclusion

  • Not only can we initialize the data in x-init, but also we can run expressions in x-init

Reference

Alpine, x-init