I am currently exploring the implementation of keyboard navigation between multiple input fields using VueJs.
Here is how the template is set up...
<div v-for="(note, index) in notes"
:key="index" ref="notex" class="input-wrapper" id="input-wrapper"
:class="{ 'focused': note.isFocused }">
<input v-model="note.value"
spellcheck="false" class="input" v-on:keydown.enter="createNextNote()"
:id="note.value ? '' : 'empty-input'"
@focus="note.isFocused = true" @blur="note.isFocused = false">
</div>
The function that executes when clicking the "ArrowUp" key (a global listener has been set up for this)
moveUp() {
const index = parseInt(Object.keys(this.notes).find(key => this.notes[key].isFocused));
if (!this.notes[index - 1]) {
return;
}
this.notes[index].isFocused = false;
this.notes[index - 1].isFocused = true;
let requiredInput = this.$refs['notex'][index - 1].firstChild;
// The reason behind using a timeout here?
setTimeout(() => requiredInput.focus(), 1);
},
Focusing on the timeout functionality.
My confusion lies in understanding the difference between employing the timeout feature and not.
Simply calling requiredInput.focus()
positions the focus in the input field but places the caret at the start.
However, by utilizing a timeout as shown above, the caret aligns behind the existing text - achieving the desired outcome.
I attempted to utilize VueJs's nextTick method, however, it results in the same positioning as without the timeout - placing the caret before the input value.
Can someone provide clarity on this distinction, please?