Keyboard Event (Arrow Keys) in Go


This post show how to detect user keypress on browsers in Go. We will use arrow keys as example and show you how to detect arrow key presses on browsers in Go/GopherJS. The full code example of this post is on my GitHub.

Detect Arrow Keys

We will attach an keyup event handler to the window object of current browser window/tab. When users press any key on the current browser window/tab, the event handler will run and we will check the keyCode property of the event. If the keyCode happens to be arrow keys, we will show which arrow key user press via div element. The div element is as follows:

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

JavaScript

GopherJS

The above code in Go/GopherJS is as follows:

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

You can also register event handler to the keyup event of document instead of window. The result is the same in this case.


References:

[1][GopherJS] Keyboard Event - Arrow Keys Example
[2][Golang] GopherJS DOM Example - Detect Keypress (Keyboard Event)
[3]JavaScript Keyboard Event (Arrow Key Example)
[4]JavaScript Arrow Key Example via event.key in Keyboard Event