To create a keyboard shortcut event listener in JavaScript
, we can add an event listener to the document
object and check if the key combination for the shortcut has been pressed.
Here's an example of how to create a listener for the Ctrl+S
key combination:
index.tsx196 chars7 lines
In this example, we first check if the Ctrl
key is being held down (event.ctrlKey
) and if the S
key has been pressed (event.key === 's'
). If both conditions are true, we can run our code to trigger the desired action. In this case, we prevent the default save action by calling event.preventDefault()
.
You can modify this example to create different keyboard shortcuts by changing the key combination and the code that will be executed when the shortcut is triggered.
gistlibby LogSnag