30

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>
Emma
  • 27,428
  • 11
  • 44
  • 69
Anton Zotov
  • 303
  • 1
  • 3
  • 5

3 Answers3

43

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>
artfulrobot
  • 20,637
  • 11
  • 55
  • 81
CD..
  • 72,281
  • 25
  • 154
  • 163
  • 2
    @AntonZotov Not surprisingly Rich Harris has a nicer solution – CD.. Jul 29 '19 at 18:44
  • 2
    Yours is nice too. I used it because I had some problems using autofocus. I did not investigate it, but it's maybe related to this chrome bug: autofocus does not work when URL contains fragment in Chrome 79: https://bugs.chromium.org/p/chromium/issues/detail?id=1046357 – voscausa Aug 18 '20 at 12:29
  • `autofocus` is not recommended these days; the Svelte language tools discourage it. Using the attribute is definitely a more elegant solution, but this is warning-free! – Jordan Mann Sep 08 '20 at 17:27
  • 2
    As best I can tell, this solution is no better for a11y than the Rich Harris solution. It simply circumvents the Svelte warning. It's fooling Svelte; but it shouldn't fool us! – pglezen Jan 30 '21 at 17:05
  • This is a great solution, because it's very flexible – khaki Jun 10 '22 at 20:54
41

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!

Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • Neither of the proposed answers work in my situation; I'll explain: I have a form with 2 inputs, and after submitting the form, I'd like to have the cursor back in the first input. Any suggestions how that should be done? Thanks! – Ad Rienks Dec 02 '19 at 23:09
  • 3
    Use `` to get a reference to the input you want to focus, then call `myInput.focus()` once the form is submitted – Rich Harris Dec 03 '19 at 21:13
  • thank you, this is a good solution! However, I desire more: not only after submission, but also before. N.B. the solution is to use autofocus! – Ad Rienks Dec 05 '19 at 00:18
  • 1
    Would you still consider it as an accessibility issue, if autofocus happen on the stage of page loading? For example: the user click on "Login" link that direct him to login page, the login page is loaded, and automatically the "Username" input field takes the focus. Does it make a difference when you're in single app application mode? – Tal Dec 29 '21 at 16:37
15

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.