sveltesveltestrap

How can I handle key{press|up|down} events with Sveltestrap components


I am trying to add some custom on:keydown handling for a SvelteStrap element; the naive approach would (seem) to be:

<script lang="ts">
  import { Card, CardBody } from 'sveltestrap';
  
  function handlekey(e) {
    // handler code goes here
  }
</script>

<Card on:keydown={handlekey}>
</Card>

In my actual code, I'm using tabindex to make the card focus-able, and I can successfully capture on:click events, but nothing seems to provoke a call to handlekey()

A simple REPL demonstrating the concept is here.


Solution

  • It seems that the SvelteStrap Card just doesn't listen on key events. You may wrap your Card into something that can listen on them :

    <script lang="ts">
      import { Card, CardBody } from 'sveltestrap'; 
        
        function handleclick(e) {
            console.log(e);
        }
        
        function handlekey(e) {
            console.log(e);
        }
    </script>
    
    <div tabindex=0 on:keydown={handlekey} on:keypress={handlekey} on:keyup={handlekey}>
        <Card on:click={handleclick}>
            <CardBody>Hello World</CardBody>
        </Card>
    </div>