Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus back on input after clicking button in Svelte?

Tags:

svelte

Use Case

I am building a chat application so whenever a user types in a message in the chat box and clicks on send, ideally it should focus back on the input. Currently, this requires the user to click on the input again to start typing.

How can this be achieved in Svelte? I tried to use the bind:this and use: directives.

Edit: This is a Svelte Sapper project.

like image 506
rohanharikr Avatar asked Oct 23 '25 09:10

rohanharikr


1 Answers

You can easily create a reference to your rendered component using bind:this={myComponentRef}. Then to focus it, just call myComponentRef.focus():

<script>
  let message = ""

  let inputRef

  const onSend = () => {
    inputRef.focus()
  }
</script>

<input bind:this={inputRef} value={message}>
<button on:click={onSend}>Send Message</button>

Have a look to the REPL.

like image 134
johannchopin Avatar answered Oct 27 '25 02:10

johannchopin