How to focus on newly added inputs in Svelte?
You can use bind:this
and tick
For example:
<script>
import { tick } from 'svelte';
let tasks = [];
async function addTask() {
let newTask = { title: "" };
tasks = [...tasks, newTask];
await tick();
newTask.input.focus();
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} bind:this={task.input} />
{/each}
<button on:click={addTask}>Add task</button>
An explanation of the advantages of my approach
What happens if the tasks
array is not initially empty?
Then methods autofocus
and use:action
have the disadvantage that when the list is initially displayed, the focus is on the last field. This may not be desirable.
My approach only controls focus when the Add button is clicked.
Rich Harris has a nicer solution
You can use use:action
:
Actions are functions that are called when an element is created.
For example:
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
function init(el){
el.focus()
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} use:init />
{/each}
<button on:click={addTask}>Add task</button>
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!