[Golang] Toggle (Show/Hide) HTML Element by GopherJS


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 toggle (show/hide) a HTML element. If you are not familiar with basic DOM manipulation in Go, read the posts in GopherJS DOM Example series first.

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 (CSS are put in the HTML file for demo, you should put CSS in a separate file in production):

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
<head>
  <title>Toggle (Show/Hide) Div Element by GopherJS</title>
  <style>
    .invisible {display: none;}
    .heading {background: yellow; width: 200px; cursor: pointer;}
    .content {background: aqua; width: 200px; height: 200px;}
  </style>
</head>
<body>
  <div id="foo" class="heading">
    <span id="foo1" class="invisible">&#9660;</span><span id="foo2">&#9658;</span>
    Heading
  </div>
  <div id="foo3" class="content invisible"><br><br>Content</div>
<script src="demo.js"></script>
</body>
</html>

We bind onclick event handler to the div element whose id is foo. If users click the element, Toggle() method of Class() are called to toggle the CSS classes to make elements visible or invisible.

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

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


func main() {
	d := dom.GetWindow().Document()
	foo := d.GetElementByID("foo").(*dom.HTMLDivElement)
	foo1 := d.GetElementByID("foo1").(*dom.HTMLSpanElement)
	foo2 := d.GetElementByID("foo2").(*dom.HTMLSpanElement)
	foo3 := d.GetElementByID("foo3").(*dom.HTMLDivElement)
	foo.AddEventListener("click", false, func(event dom.Event) {
		foo1.Class().Toggle("invisible")
		foo2.Class().Toggle("invisible")
		foo3.Class().Toggle("invisible")
	})
}

Compile the Go code to JavaScript by:

$ gopherjs build toggle.go -o demo.js

Put demo.js together with the index.html in the same directory. Open the index.html with your browser. Click the yello Heading to toggle (show/hide) the HTML element.


Tested on: Ubuntu Linux 15.10, Go 1.5.3.