1.0.0 • Published 11 months ago

svelte-focus-key v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

svelte-focus-key

NPM

Svelte component and action to focus an element when pressing a key

The primary use case is to focus a search input when pressing the forward slash key ("/").

Installation

# Yarn
yarn add -D svelte-focus-key

# NPM
npm i -D svelte-focus-key

# pnpm
pnpm i -D svelte-focus-key

Usage

FocusKey component

Use the bind:this directive to pass the element to focus to the FocusKey component.

<script>
  import FocusKey from "svelte-focus-key";

  let element;
</script>

<input bind:this={element} placeholder={'Press "/" to focus'} />

<FocusKey {element} />

Custom focus key

The default focus key is the forward slash (/). Customize the key using the key prop.

<script>
  import FocusKey from "svelte-focus-key";

  let textarea;
</script>

<textarea bind:this={textarea} placeholder={'Press "s" to focus'} />

<FocusKey element={textarea} key="s" />

Multiple focus keys

The key prop can also accept an array of keys.

<script>
  import FocusKey from "svelte-focus-key";

  let node;
</script>

<input bind:this={node} placeholder={'Press "a" or "b"'} />

<FocusKey element={node} key={["a", "b"]} />

Combination of keys

A combination of keys should be separated by a +.

<script>
  import FocusKey from "svelte-focus-key";

  let element;
</script>

<input bind:this={element} placeholder={'Press "⌘+k" to focus'} />

<FocusKey {element} key="Meta+k" />

Select text on focus

Set selectText to true to select the text in the element when focusing.

<script>
  import FocusKey from "svelte-focus-key";

  let input;
</script>

<input
  bind:this={input}
  value={'Press "e" to focus'}
  placeholder={'Press "e" to focus'}
/>

<FocusKey element={input} key="e" selectText />

focusKey action

This utility also provides a Svelte action.

<script>
  import { focusKey } from "svelte-focus-key";
</script>

<input use:focusKey={{ key: "q" }} placeholder={'Press "q" to focus'} />

API

Props

NameDescriptionTypeDefault value
elementHTML element to focusHTMLElementnull
keyKey to trigger focus when pressedstring or string[]"/"
selectTextSelect element text when focusingbooleanfalse

The focusKey action has the same props as FocusKey except for element.

1.0.0

11 months ago

0.3.0

2 years ago

0.2.1

2 years ago

0.3.2

2 years ago

0.2.3

2 years ago

0.3.1

2 years ago

0.2.2

2 years ago

0.2.4

2 years ago

0.2.0

2 years ago

0.1.1

3 years ago

0.1.0

3 years ago