Using keyboard events
Handling keyboard events in normal web applications is not so common. However, if you are writing a web game, you'll almost certainly want to catch arrow key input, and the like. This recipe shows us how we can handle those events.
How to do it...
Look at the keyboard
project. The web page is a copy of the page used in the Preventing an onSubmit event recipe, but now submit stays enabled. Suppose we also want to ensure that pressing the Enter key provokes submit
, just like clicking on the submit button.
To that end, we add the following event listener to
main()
:document.onKeyPress.listen(_onKeyPress);
The
_onKeyPress
method is as follows:_onKeyPress(KeyboardEvent e){ if (e.keyCode == KeyCode.ENTER) submit(e); }
Now, pressing Enter will cause the form to be submitted.
How it works...
The document
object from dart:html
has three events to work with key input: onKeyPress
, onKeyDown
, and onKeyUp
. They all generate a stream of KeyboardEvent
objects that capture user interaction...