[Golang] Input Text Element Enter Keypress Event by GopherJS
Introduction
In this post, we will give an example of DOM manipulation in Go program. This example shows how to detect enter keypress event of the input text element and register an event handler to it.
Install GopherJS
Run the following command to install GopherJS:
$ go get -u github.com/gopherjs/gopherjs
Source Code
HTML code:
1 2 3 4 5 6 7 8 9 10 | <!doctype html> <html> <head> <title>Golang Input Text Element Enter Key Event</title> </head> <body> <input id="foo" type="text"> <script src="demo.js"></script> </body> </html> |
Go code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package main import "github.com/gopherjs/gopherjs/js" func handleInputKeyUp(event *js.Object) { if keycode := event.Get("keyCode").Int(); keycode == 13 { // user press enter key print("enter key") } } func main() { foo := js.Global.Get("document").Call("getElementById", "foo") foo.Call("addEventListener", "keyup", handleInputKeyUp, false) } |
Compile the Go code to JavaScript by:
$ gopherjs build enter.go -o demo.js
Put demo.js together with the index.html in the same directory. Open the index.html with your browser and also the browser console. Press enter in the input and you will see the message.
Tested on: Ubuntu Linux 15.10, Go 1.5.3, Chromium Version 48.0.2564.82 Ubuntu 15.10 (64-bit).
References:
[1] | GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, ) |
[2] | Bindings · gopherjs/gopherjs Wiki · GitHub |
[3] | dom - GopherJS bindings for the JavaScript DOM APIs (GitHub) |
[4] | input text enter event |
[5] | Trigger a button click with JavaScript on the Enter key in a text box - Stack Overflow |