1 // Package xjs provides some simple, but often needed shortcut funcs for gopherJS 2 package xjs // import "vimagination.zapto.org/gopherjs/xjs" 3 4 import ( 5 "fmt" 6 "strings" 7 8 "github.com/gopherjs/gopherjs/js" 9 10 "honnef.co/go/js/dom" 11 ) 12 13 // body var used to cache the wrapped body once Body is sucessfully called 14 var body *dom.HTMLBodyElement 15 16 // Body gets the document's body element 17 func Body() *dom.HTMLBodyElement { 18 if body == nil { 19 o := js.Global.Get("document").Get("body") 20 if o == nil || o == js.Undefined { 21 return nil 22 } 23 body = &dom.HTMLBodyElement{BasicHTMLElement: &dom.BasicHTMLElement{&dom.BasicElement{&dom.BasicNode{js.Global.Get("document").Get("body")}}}} 24 } 25 return body 26 } 27 28 // RemoveChildren removes all of the child nodes of the node given 29 func RemoveChildren(node dom.Node) dom.Node { 30 n := node.Underlying() 31 for n.Call("hasChildNodes").Bool() { 32 n.Call("removeChild", n.Get("lastChild")) 33 } 34 return node 35 } 36 37 // SetInnerText removes all child nodes from the given node and sets a single 38 // Text Node with the given string 39 func SetInnerText(node dom.Node, text string) dom.Node { 40 n := node.Underlying() 41 for n.Call("hasChildNodes").Bool() { 42 n.Call("removeChild", n.Get("lastChild")) 43 } 44 n.Call("appendChild", js.Global.Get("document").Call("createTextNode", text)) 45 return node 46 } 47 48 // SetPreText does similar to SetInnerText, but linebreaks are converted to <br />s 49 func SetPreText(node dom.Node, text string) dom.Node { 50 n := node.Underlying() 51 for n.Call("hasChildNodes").Bool() { 52 n.Call("removeChild", n.Get("lastChild")) 53 } 54 for i, part := range strings.Split(text, "\n") { 55 if i > 0 { 56 n.Call("appendChild", js.Global.Get("document").Call("createElement", "br")) 57 } 58 n.Call("appendChild", js.Global.Get("document").Call("createTextNode", part)) 59 } 60 return node 61 } 62 63 // CreateElement is a shortcut to create an element with the given name 64 func CreateElement(name string) dom.Element { 65 return dom.WrapElement(js.Global.Get("document").Call("createElement", name)) 66 } 67 68 // Alert provides for formated alert boxes 69 func Alert(format string, params ...interface{}) { 70 js.Global.Call("alert", fmt.Sprintf(format, params...)) 71 } 72 73 // Text creates a text node containing the givin text 74 func Text(text string) *dom.Text { 75 return &dom.Text{&dom.BasicNode{js.Global.Get("document").Call("createTextNode", text)}} 76 } 77 78 // AppendChildren appends all the given children to the parent. 79 func AppendChildren(parent dom.Node, children ...dom.Node) dom.Node { 80 for _, child := range children { 81 parent.AppendChild(child) 82 } 83 return parent 84 } 85 86 // Log prints a formatted string to the javascript console 87 func Log(format string, params ...interface{}) { 88 js.Global.Get("console").Call("log", fmt.Sprintf(format, params...)) 89 }