點燈坊

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

Using $nextTick to Execute Expression after DOM Updates

Sam Xiao's Avatar 2022-01-26

If we want to execute some expression after DOM updates, we can pass the function to the $nextTick magic property.

Version

Alpine 3.9

$nextTick

nexttick000

Set focus on textbox after showing the textbox.

<!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>
    <style>
      [x-cloak] {
        display: none !important;
      }
    </style>
  </head>
  <body x-data="{ isComment: false }">
    <div x-cloak x-show="isComment">
      <textarea x-ref="textarea">Comment text...</textarea>
      <dvi>
        <button>Submit</button>
      </dvi>
    </div>
    <div x-show="!isComment">
      <p>Comment text...</p>
      <button
        @click="isComment = true; $nextTick(() => $refs.textarea.focus())"
      >
        Comment
      </button>
    </div>
  </body>
</html>

Line 14

<body x-data="{ isComment: false }">
  • isComment : a variable to control x-show

Line 21

<div x-show="!isComment">
  <p>Comment text...</p>
  <button
    @click="isComment = true; $nextTick(() => $refs.textarea.focus())"
  >
    Comment
  </button>
</div>
  • x-show : show <div> according to isComment
isComment = true
$nextTick(() => $refs.textarea.focus())
  • Set isComment to true to show textarea, but we also want to set focus on textarea
  • $refs.textarea.focus() has to be wrapped to a function and pass it to $nextTick
  • Alpine will execute the expression after DOM updates

Line 15

<div x-cloak x-show="isComment">
  <textarea x-ref="textarea">Comment text...</textarea>
  <dvi>
    <button>Submit</button>
  </dvi>
</div>
  • x-show : show <div> according to isComment
  • x-cloak : prevent page flicker after page loads
  • x-ref : set a name for the element

Conclusion

  • Set focus is a classical use case for $nextTick

Reference

Alpine, $nextTick