Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus on newly added inputs in Svelte?

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>
like image 428
Anton Zotov Avatar asked Jul 29 '19 15:07

Anton Zotov


People also ask

How do you set the focus on an input field?

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.

How do you know if input field is focused?

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.


1 Answers

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!

like image 160
Rich Harris Avatar answered Sep 28 '22 06:09

Rich Harris