[Golang] GopherJS DOM Example - Detect Keypress (Keyboard Event)


Introduction

It is really cool to run Go code in the browser. GopherJS is a compiler from Go to JavaScript, which makes this possible. In this post, we will give an example of DOM manipulation in Go program. This example shows how to detect user keypress. addEventListener function is used to attach an onkeydown (keyboard event) handler to window object. In the event handler, the keycode of the keyboard event will be printed out.

Install GopherJS and DOM bindings

Run the following command to install GopherJS and GopherJS bindings for the JavaScript DOM APIs:

$ go get -u github.com/gopherjs/gopherjs
$ go get -u honnef.co/go/js/dom

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Detect Keypress (Keyboard Event)</title>
</head>
<body>
  <div>Current KeyCode: <span id="foo"></span></div>
  <script src="demo.js"></script>
</body>
</html>

We attach an onkeydown event handler to the window object. When users press any key, the keycode of the keyboard event is printed out.

keycode.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "honnef.co/go/js/dom"
import "strconv"

func main() {
	w := dom.GetWindow()
	s := w.Document().GetElementByID("foo")

	w.AddEventListener("keydown", false, func(event dom.Event) {
		ke := event.(*dom.KeyboardEvent)
		s.SetInnerHTML(strconv.Itoa(ke.KeyCode))
	})
}

The above code is very similar to JavaScript counterpart. Note that dom.Event is casted to dom.KeyboardEvent by type assertions. Now compile the Go code to JavaScript by:

$ gopherjs build keycode.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. Press any key and you will see the keycode of the keypress.


Tested on: Ubuntu Linux 15.10, Go 1.5.2.