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 write a dropdown menu. This example is ported from the
Dart dropdown menu [5] and JavaScript dropdown menu [6].
If you are not familiar with basic DOM manipulation in Go, read the
posts in GopherJS DOM Example series first.
<!doctype html><html><head><title>Golang Dropdown Menu by GopherJS</title><linkrel="stylesheet"type="text/css"href="style.css"></head><body><divid="menu-dropdown">Menu▼</div><divid="menuDiv-dropdown"class="invisible">
line1<br>line2<br>line3
</div><scriptsrc="demo.js"></script></body></html>
We will bind a onclick event handler to the HTML DOM document object.
When users click inside the browser, we will check which DOM element is clicked.
According to the clicked element and visibility of the dropdown menu, the
dropdown menu will show up or disappear.
packagemainimport"honnef.co/go/js/dom"funccheckParent(target,elmdom.Element)bool{fortarget.ParentElement()!=nil{iftarget.IsEqualNode(elm){returntrue}target=target.ParentElement()}returnfalse}funcmain(){d:=dom.GetWindow().Document()toggle:=d.GetElementByID("menu-dropdown").(*dom.HTMLDivElement)menu:=d.GetElementByID("menuDiv-dropdown").(*dom.HTMLDivElement)d.AddEventListener("click",false,func(eventdom.Event){if!checkParent(event.Target(),menu){// click NOT on the menuifcheckParent(event.Target(),toggle){// click on the linkmenu.Class().Toggle("invisible")}else{// click both outside link and outside menu, hide menumenu.Class().Add("invisible")}}})}
Put demo.js together with the index.html and style.css in the same
directory. Open the index.html with your browser. Click on the Menu text to
toggle the visibility of the menu. Also try to click outside the dropdown menu,
the dropdown menu will disappear.