I use #each to display an input for every member of the tasks
array. When I click the Add task button, a new element is inserted into the array, so a new input appears in the #each loop.
How do I focus the input that's been added upon clicking the Add task button?
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} />
{/each}
<button on:click={addTask}>Add task</button>
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input. to check if the input element is focused.
You can use the autofocus
attribute:
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} autofocus />
{/each}
<button on:click={addTask}>Add task</button>
Note that you'll get an accessibility warning. That's because accessibility guidelines actually recommend that you don't do this:
People who are blind or who have low vision may be disoriented when focus is moved without their permission. Additionally, autofocus can be problematic for people with motor control disabilities, as it may create extra work for them to navigate out from the autofocused area and to other locationso on the page/view.
It's up to you to determine whether this advice is relevant in your situation!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With