Keystroke handling in Svelte

How to handle keystroke in Svelte

Implementing keystroke in Svelte can be achieved using the <svelete:window></svelte.window> component.

Suppose I want to do some action on Enter key press (input fields), it can be done as follows.

Add the <svelte:window> in your template section of a component/route.

OnEnter is the event handler which can be defined in the script section, will accepts the event as argument.

const onEnter =(event)=>{ 
     if(event.key === "Enter"){        
        console.log("Enter key pressed");
        goto('/bakes')
     }
    }	  

Input and keystroke

The above method will fired whenever you press enter key, no matter which input field you were in. There can be multiple input fields in a page. To work with specific field, we have to use the Input fields keydown event.

<input type="text" on:keydown={onEnter} 
bind:value={value}  > 

Comments

huInvalid Date

😂

LailaInvalid Date

Welcome

Write your comment