2

[Golang] GopherJS DOM Example - Hide Element by display:none

 2 years ago
source link: http://siongui.github.io/2016/01/13/gopherjs-dom-example-hide-element-by-display-none/
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.

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw

<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Hide Element by display:none</title>
</head>
<body>

<div id="foo">Click me to hide me</div>

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

We will bind a onclick event handler to the div element whose id is foo. When users click the div element, the display property of the div element is set to none, which hides the div element.

hide.go | repository | view raw

package main

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

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

	foo := d.GetElementByID("foo").(*dom.HTMLDivElement)
	foo.AddEventListener("click", false, func(event dom.Event) {
		foo.Style().SetProperty("display", "none", "")
	})
}

Note that to call Style(), we must assert the type of foo to HTMLDivElement. Compile the Go code to JavaScript by:

$ gopherjs build hide.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. Click the text and it will disappear!


Tested on: Ubuntu Linux 15.10, Go 1.5.2.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK