8

[Golang] Input Text Element Enter Keypress Event by GopherJS

 2 years ago
source link: http://siongui.github.io/2016/02/01/go-input-text-element-enter-event-by-gopherjs/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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:

index.html | repository | view raw

<!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:

enter.go | repository | view raw

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:

[2]Bindings · gopherjs/gopherjs Wiki · GitHub

[4]input text enter event

[5]Trigger a button click with JavaScript on the Enter key in a text box - Stack Overflow


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK