Skip to content

<svelte:window on:keydown /> event.preventDefault() does nothing #15474

@andykais

Description

@andykais

Describe the bug

I discovered that the svelte:window keydown event is not a native browser keydown event. This came up because I have a use case of using the "/" key to focus an input element, but I have no (clean) way to prevent the "/" key from being written to the input element using the svelte handler.

I have a workaround that is fine (just using the native browser keydown event). Just pointing out that it feels like this is a weird reason to need to use the browser native listener and move out of the svelte ecosystem.

Reproduction

the following snippet will focus the input element and write the "/" character to the input element. What I want to happen is just focus the input and ignore the "/" character.

<script>
  function handle_keydown(e) {
    if (e.code === 'KeySlash') {
      e.preventDefault()
      input.focus()
    }

  let input
  }
</script>

<svelte:window on:keydown={handle_keydown} />

<input bind:this={input} />

I have proven that this is an issue with the svelte keydown event specifically because I can accomplish the behavior I want with document.addEventListener('keydown', handle_keydown).

Logs

System Info

using firefox 136.0, Svelte kit:

	"devDependencies": {
		"@deno/vite-plugin": "^1.0.4",
		"@sveltejs/adapter-auto": "^4.0.0",
		"@sveltejs/kit": "^2.16.0",
		"@sveltejs/vite-plugin-svelte": "^5.0.0",
		"@tailwindcss/vite": "^4.0.0",
		"svelte": "^5.0.0",
		"svelte-check": "^4.0.0",
		"tailwindcss": "^4.0.0",
		"typescript": "^5.0.0",
		"typescript-svelte-plugin": "^0.3.45",
		"vite": "^6.0.0"
	},


running on deno.

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions