1

I am trying to get keyup event on a specific element in svelte but it seems it is not possible. I checked this REPL and also I tried by adding the event to the document and it worked fine. But I don't want to add it to the document and I just want to have it on my element.

<script>
    const key = () => {
        console.log('key')
    }
</script>

<div
    on:keyup={key}
     style="width:100%; height:200px; border:2px solid #ff0000;"></div>
Mohammad Taherian
  • 1,622
  • 1
  • 15
  • 34
  • 1
    Why do you *just want to have it on the element*? I think the div needs to be focused so that the key events are emitted. For that it needs to have a `tabindex` https://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function – Corrl Dec 28 '22 at 18:25
  • As Corrl just stated.. Another resource: https://stackoverflow.com/questions/6633248/how-to-grab-keyboard-events-on-an-element-which-doesnt-accept-focus – Thomas Hennes Dec 28 '22 at 18:29
  • Thank you gentlemen for the comments, but even if you focus on the element it won't work. Please note that I am trying to do that in a svelte project. It seems the event does not exist at all. You can try it on a REPL. – Mohammad Taherian Dec 28 '22 at 18:47
  • 1
    It *does* work: [REPL](https://svelte.dev/repl/33e2636a9205412c8f3a6d48d362d8d7?version=3.55.0). Click inside the div then press any key and watch the console log get updated. – Thomas Hennes Dec 28 '22 at 20:07
  • Aletrnative version with autofocus on div: [REPL](https://svelte.dev/repl/c48507dfcf6446cd8f0def8480374310?version=3.55.0). Just press any key and watch the log get updated. – Thomas Hennes Dec 28 '22 at 20:10

0 Answers0