[Golang] GopherJS DOM Example - Toggle (Play/Pause) Sound on Click Event


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 simple example of DOM manipulation in Go program. This example shows how to toggle (play/pause) sound by clicking 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:

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Toggle (Play/Pause) Sound on Click Event</title>
</head>
<body>

<button id="foo" type="button">Click Me to Play Sound</button>
<audio id="audio">
  <source src="Wat_Metta_Buddha_Qualities.mp3" type="audio/mpeg">
Your browser does not support this audio format.
</audio>

<script src="demo.js"></script>
</body>
</html>

We will bind a onclick event handler to the button element whose id is foo. When users click the button, we will check if the playing of the audio is paused or not. If it is paused, call the play() method of HTML audio element to play the sound of the mp3 file, which is Wat_Metta_Buddha_Qualities.mp3 in this example. If the audio is not paused, call the pause() method of HTML audio element to stop playing.

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

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

func main() {
	d := dom.GetWindow().Document()

	foo := d.GetElementByID("foo").(*dom.HTMLButtonElement)
	foo.AddEventListener("click", false, func(event dom.Event) {
		a := d.GetElementByID("audio").(*dom.HTMLAudioElement)
		if a.Paused {
			a.Play()
			foo.SetTextContent("Click Me to Pause Sound")
		} else {
			a.Pause()
			foo.SetTextContent("Click Me to Play Sound")
		}
	})
}

Compile the Go code to JavaScript by:

$ gopherjs build toggle.go -o demo.js

Put demo.js together with the index.html and the mp3 file in the same directory. Open the index.html with your browser. Click the button to play the sound, and click it again to stop it!


Tested on: Ubuntu Linux 15.10, Go 1.5.3.