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
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 controlx-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 toisComment
isComment = true
$nextTick(() => $refs.textarea.focus())
- Set
isComment
totrue
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 toisComment
x-cloak
: prevent page flicker after page loadsx-ref
: set a name for the element
Conclusion
- Set focus is a classical use case for
$nextTick