Element Position (Scroll Included) in Go


This post will show you how to get HTML DOM element position, including scroll position of the document, in Go/GopherJS. An example of getting element position is to show the tooltip when the mouse hovers over texts [2]. We need to get the position of the text and show the tooltip next to the text.

Get HTML DOM Element Position

JavaScript

function GetPosition(elm) {
  var x = elm.getBoundingClientRect().left + window.pageXOffset;
  var y = elm.getBoundingClientRect().top + window.pageYOffset;
  return [x, y];
}

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

func GetPosition(elm *js.Object) (x, y float64) {
      x = elm.Call("getBoundingClientRect").Get("left").Float() +
              js.Global.Get("pageXOffset").Float()
      y = elm.Call("getBoundingClientRect").Get("top").Float() +
              js.Global.Get("pageYOffset").Float()
      return
}

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

func GetPosition(elm *Object) (x, y float64) {
      x = elm.GetBoundingClientRect().Left() + Window.PageXOffset()
      y = elm.GetBoundingClientRect().Top() + Window.PageYOffset()
      return
}

The full code example of this post is on my GitHub.


References:

[1]JavaScript DOM Element Position (Scroll Position Included)
[2][JavaScript] Show Note on Mouse Hovering Over Text