[GopherJS] Keyboard Event - Arrow Keys Example


Keyboard event of arrow keys via GopherJS.

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>GopherJS keyboard event - arrow keys demo</title>
</head>
<body>

<div id="info">Press any arrow keys</div>

<script src="app.js"></script>
</body>
</html>
app.go | 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
package main

import "github.com/gopherjs/gopherjs/js"

const (
	LEFT  = 37
	UP    = 38
	RIGHT = 39
	DOWN  = 40
)

func main() {
	info := js.Global.Get("document").Call("getElementById", "info")

	js.Global.Call("addEventListener", "keyup", func(event *js.Object) {
		keycode := event.Get("keyCode").Int()
		if keycode == LEFT {
			info.Set("innerHTML", "left arrow key")
		}
		if keycode == UP {
			info.Set("innerHTML", "up arrow key")
		}
		if keycode == RIGHT {
			info.Set("innerHTML", "right arrow key")
		}
		if keycode == DOWN {
			info.Set("innerHTML", "down arrow key")
		}
	}, false)
}

The keyup event of window object (which is js.Global in GopherJS) is listened. You can also bind the event listener to input element or textarea element depending on the needs of your application.

To see demo: use GopherJS to compile app.go to app.js. Put index.html and app.js in the same directory. Open index.html with your browser.


Tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.4
  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]