He/him, developer, builder of things both tangible and abstract, practitioner of yoga and ukulele... All-around complicated monkey.
https://www.buymeacoffee.com/tobyplaystheuke
Recently, there was a question in the Odin Project's Discord group about handling event listeners - in particular, "can we bind a key to a given element or action?" Key-binding is a useful utility, and can be done with vanilla js,but it could be handy to bind directly to a keystroke, rather than to all keyup events.
With that, for example, we could do a simple js game loop. We can listen for arrow keys or specific action keys, and check for modifiers on them, and respond appropriately.
And we're not having to duplicate the if(e.key==='ArrowLeft'') or if(e.key==='ArrowUp') checks each time. We bind to a custom event indicating which key is pressed: in effect, key binding.
Here's the code I put together in playing with this one.
Recently, there was a question in the Odin Project's Discord group about handling event listeners - in particular, "can we bind a key to a given element or action?" Key-binding is a useful utility, and can be done with vanilla js,but it could be handy to bind directly to a keystroke, rather than to all keyup events.
To see what I mean, we could do things like this:
With that, for example, we could do a simple js game loop. We can listen for arrow keys or specific action keys, and check for modifiers on them, and respond appropriately.
And we're not having to duplicate the
if(e.key==='ArrowLeft'')orif(e.key==='ArrowUp')checks each time. We bind to a custom event indicating which key is pressed: in effect, key binding.Here's the code I put together in playing with this one.
And to tinker with it: replit.com/@TobiasParent/CustomKey...