By Vivek - November 10, 2020
Focus a Dynamic Input Field in Svelte
When a user adds a new row, tag, address, or form field, focus should usually move straight to the new input. In Svelte, the two practical options are a reusable action or the native autofocus attribute. The action approach is more reliable for dynamically added fields because it runs when the element is created.
Table of Contents
- Use a Svelte action
- Use autofocus for simple cases
- Common mistakes
- Frequently asked questions
- Related Svelte guides
use:action
Actions are functions that are called when an element is created.
<script>
let inputs = [];
function addInput() {
inputs = […inputs, { title: "" }];
}
function callFocus(input){
input.focus();
}
</script>
{#each inputs as i}
<input type="text" bind:value={i.title} use:callFocus />
{/each}
<button on:click={addInput}>Add Input Field</button> This works because use:callFocus receives the actual DOM node after Svelte creates it. If you want to reuse the behavior across components, rename the action to something like autoFocus and keep it in a shared helper file.
autofocus Attribute:
<script>
let inputs = [];
function addInput() {
inputs = […inputs, { title: "" }];
}
</script>
{#each inputs as i}
<input type="text" bind:value={i.title} autofocus />
{/each}
<button on:click={addInput}>Add Input Field</button> autofocus is fine when the element is present on initial page load. For repeated dynamic additions, prefer the action because it does not depend on browser-specific autofocus timing.
Common mistakes
Calling focus before the input exists
If you call input.focus() immediately after updating an array, the DOM may not have rendered the new input yet. An action avoids this because Svelte runs it after the element is mounted.
Reusing the same object without a key
When focusing items in an {#each} block, use stable data and a keyed each block if items can be inserted or removed from the middle.
{#each inputs as input (input.id)}
<input bind:value={input.title} use:callFocus />
{/each} Frequently Asked Questions
Related Svelte guides
Related Posts
- Build a Chrome Extension with Svelte
- Svelte Tutorial - A Thorough Introduction to SvelteJs
- How to Deploy a SvelteKit App to Firebase
- How to Install Node.js and NPM on Ubuntu
- AWS Lambda Function with Response Streaming using Node.js
- Install Bootstrap in SvelteKit
- How to Dockerize A Svelte App
- How to import CSS from node_modules in Svelte
- How to fix Nginx 403 Forbidden Error
- Linked List Implementation in C++ - A Step by Step Guide