[Golang] GopherJS DOM Example - Event Binding (addEventListener)


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 a very simple example of DOM manipulation in Go program. This example uses addEventListener to attach an event handler to specific DOM element.

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 - Event Binding (addEventListener)</title>
</head>
<body>
  <div id="foo">Click Me</div>
  <script src="demo.js"></script>
</body>
</html>

We will attach an onclick event handler to the div element whose id is foo. When users click the div element, the content of the div element will be changed, and print a message on the browser console.

bind.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"

func main() {
	d := dom.GetWindow().Document()
	h := d.GetElementByID("foo")

	h.AddEventListener("click", false, func(event dom.Event) {
		event.PreventDefault()
		h.SetInnerHTML("I am Clicked")
		println("This message is printed in browser console")
	})
}

As the above code show, the event registration is almost the same as JavaScript counterpart. The println will print messages on browser console, which is the same as console.log in JavaScript. Now compile the Go code to JavaScript by:

$ gopherjs build bind.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. You will see the text Click Me in the browser window. Open your browser console, click the text, you will see the text becomes I am Clicked and the message This message is printed in browser console. is printed on the console.

See Also [GopherJS] Register Event Handler (Event Binding)


Tested on: Ubuntu Linux 15.10, Go 1.5.2.