0

I would like to shift focus on my page in response to keyboard input. With Svelte it seems that the simplest way is to use the autofocus attribute. However I cannot get conditional autofocus attributes to work.

Here's a simple repro of my problem: https://svelte.dev/repl/0861d097921d4a35957f016a8c35cfe6?version=3.44.3

Am I doing something wrong or is this not possible in Svelte 3?

Conditional autofocus was possible in a previous version of Svelte according to this question: Sveltejs render html attribute conditionally

And conditionality is possible for other attributes in Svelte 3 according to this question: How to have a conditional attribute in Svelte 3?

Dan
  • 7,446
  • 6
  • 32
  • 46

2 Answers2

0

One solution could be to add a key block around the thing to make it re-run on every update of the focusIndex.

Example

{#key focusIndex}
    {#each items as item, index}
        <input autofocus="{index === focusIndex}" value={item} on:keydown={(ev) => test(ev)} />
    {/each}
{/key}

Not the prettiest solution, but might unblock you.

Oskar Hane
  • 1,824
  • 13
  • 8
  • Thanks, this does work, but seems inefficient. I'll wait a little longer to see if there's a better way before accepting this answer. – Dan Dec 22 '21 at 08:15
  • Hmm, my real code is more complicated than the example, and this approach also messes up my blur/focus handling (I think because the element gaining focus gets destroyed by the refresh) – Dan Dec 22 '21 at 08:56
0

Not strictly an answer to the exact question I asked, but the alternative that I've gone with is to use bind:this on the elements to create an array of the DOM elements and then in the keydown handler explicitly call .focus() on the DOM elements.

Example: https://svelte.dev/repl/83934cd7924741a8a4c5a620f79d5bb5?version=3.44.3

Dan
  • 7,446
  • 6
  • 32
  • 46