S
SolidJS•2y ago
Bersaelor

onKeyPress event

Hello there, I'm trying to capture key-presses to make a gallery go left/right with the arrow keys. In react I would do:
<div tabIndex="0" onKeyPress={(e) => console.log("onKeyPress: ", e)}></div>
<div tabIndex="0" onKeyPress={(e) => console.log("onKeyPress: ", e)}></div>
yet, when I do that in solidjs I don't see anything printed in the console. I must be missing something really simple, can anyone help me out?
12 Replies
Alex Lohr
Alex Lohr•2y ago
Could you add some content to the div so you can actually focus it?
Bersaelor
BersaelorOP•2y ago
@lexlohr I tried
<div class={styles.boxImageControl} tabIndex="0" onKeyDown={(e) => console.log("onKeyDown: ", e)}>
<div class={styles.boxImageControl} tabIndex="0" onKeyDown={(e) => console.log("onKeyDown: ", e)}>
but it still didn't send anythign to the console
Alex Lohr
Alex Lohr•2y ago
Sorry, I'm on my mobile, which makes it difficult to test this myself.
Bersaelor
BersaelorOP•2y ago
Bersaelor
BersaelorOP•2y ago
thank you for taking the time to answer on your mobile 😉 so there is definitely content, and I can also see the tabIndex="0" being set
Alex Lohr
Alex Lohr•2y ago
Looks like the buttons inside might catch the focus.
Bersaelor
BersaelorOP•2y ago
mhm, if I first click on the div, and then press a button it starts to have focus and then consumes my keydown
Bersaelor
BersaelorOP•2y ago
but I don't want the use to have to click anywhere also as soon as I click anywhere else the focus is gone again i also tried
const handleKeyPress = (event: Event) => {
console.log(event)
}

onMount(() => {
window.addEventListener('onKeyDown', handleKeyPress);
});
const handleKeyPress = (event: Event) => {
console.log(event)
}

onMount(() => {
window.addEventListener('onKeyDown', handleKeyPress);
});
but that doesn't seem to be called at all
Alex Lohr
Alex Lohr•2y ago
You could use actual events using on:keypress or even oncapture:keypress, if you intend to stop the event's propagation.
Alex Lohr
Alex Lohr•2y ago
You might need to extend the JSX namespace to satisfy typescript: https://www.solidjs.com/docs/latest/api#special-jsx-attributes
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
Alex Lohr
Alex Lohr•2y ago
If you want to capture global key events, you need to use document.
Bersaelor
BersaelorOP•2y ago
yeah, it was the document vs window
Want results from more Discord servers?
Add your server