Skip to content

Instantly share code, notes, and snippets.

@benvp
Created July 17, 2020 13:30
Show Gist options
  • Save benvp/9f75733e292395a16a79c88e54f1288d to your computer and use it in GitHub Desktop.
Save benvp/9f75733e292395a16a79c88e54f1288d to your computer and use it in GitHub Desktop.
<script>
function autocomplete() {
return {
// ...
scrollTo(idx) {
this.$refs[`item-${idx}`]?.scrollIntoView(false);
},
focusNext() {
const nextIndex = this.focus + 1;
const total = this.$refs.suggestions?.childElementCount ?? 0;
if (this.isOpen && nextIndex < total) {
this.setFocus(nextIndex)
this.scrollTo(nextIndex);
}
},
focusPrev() {
const nextIndex = this.focus - 1;
if (this.isOpen && nextIndex >= 0) {
this.setFocus(nextIndex);
this.scrollTo(nextIndex);
}
},
// ...
}
}
</script>
<!--
add the following attributes to the
autocomplete div container
-->
<div
x-on:keydown.arrow-up="focusPrev"
x-on:keydown.arrow-down="focusNext"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment