[Dart] Keyboard Event (Arrow Key Example)


This is Dart verion of my previous post JavaScript Keyboard Event (Arrow Key Example) [1].

Demo (view with Dartium)

Source Code for Demo (HTML):

arrow-key.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Dart Arrow Key Event Example</title>
</head>
<body>

Press Any Key:<br>
<textarea id="info" rows="20" cols="80"></textarea>

<script type='text/javascript'>
  var script = document.createElement('script');
  if (navigator.userAgent.indexOf('(Dart)') === -1) {
    // Browser doesn't support Dart
    script.setAttribute("type","text/javascript");
    script.setAttribute("src", "arrow-key.js");
  } else {
    script.setAttribute("type","application/dart");
    script.setAttribute("src", "arrow-key.dart");
  }
  document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
</html>

Source Code for Demo (Dart):

arrow-key.dart | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import 'dart:html';

void arrowKeystrokes(Event e) {
  if(e is KeyboardEvent) {
    KeyboardEvent kevt = e as KeyboardEvent;

    switch(kevt.keyCode) {
      case KeyCode.LEFT:
        querySelector("#info").appendHtml("LEFT ");
        break;

      case KeyCode.UP:
        querySelector("#info").appendHtml("UP ");
        break;

      case KeyCode.DOWN:
        querySelector("#info").appendHtml("DOWN ");
        break;

      case KeyCode.RIGHT:
        querySelector("#info").appendHtml("RIGHT ");
        break;

      default:
        querySelector("#info").appendHtml("SOMEKEY ");
    }
  }
}

void main() {
  window.onKeyUp.listen(arrowKeystrokes);
}

References:

[1]JavaScript Keyboard Event (Arrow Key Example)
[2]How to listen for a keyboard event in dart programming
[3]How to trigger a KeyboardEvent in Dart
[4]How to change Element innerHtml to Dart SDK 0.7.1
[5]Dart: how to dynamically set document's body's innerHTML
[6]Dart KeyCode source code
[7]Dart KeyCode abstract class