My journey with vue.js
programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of
document.getElementById('myTextBox').focus()
.
The scenario is that initially, the textbox is hidden. Upon clicking a "Start" button, the textbox gets displayed, and I want to focus on it at that point. I attempted using ref
, but couldn't get it to work (refer to code snippet below).
HTML:
<input id="typeBox" ref="typeBox" placeholder="Type here..." />
Javascript
export default {
name: 'game',
methods: {
startTimer () {
setTimeout(function () { /* .focus() won't work without this */
/* ugly and not recommended */
// document.getElementById('typeBox').focus()
/* Throws the error: Cannot read property 'typeBox' of undefined */
this.$refs.typeBox.focus()
// ... any other options?
// ...
}, 1)
}
} /* END methods */
} /* END export default */
Is there anyone who can assist me with achieving this? Your guidance will be highly appreciated.
UPDATE:
Including autofocus
attribute on the input
element helps in focusing immediately after the page loads. However, in my application, I need to re-focus on the input field multiple times without page reload, which is why I need a way to trigger .focus()
programmatically.