getOffsetTop
getOffsetTop returns the offsetTop of an element relative to a given parent. Because element.offsetTop is only measured against the nearest offsetParent, this function walks up the offsetParent chain recursively, adding up each offsetTop until it reaches the parent you specify.
It accepts three arguments:
| Argument | Type | Default | Description |
|---|---|---|---|
el | HTMLElement | — | The element you want the offset for. |
parent | HTMLElement | document.body | The ancestor you want the offset measured relative to. |
offsetTop | number | 0 | The starting value. This is used internally by the recursion — leave it as-is. |
Usage examples
Basic
- 2.0 Build
- 1.0 Build
// Distance from the top of the document body
const offset = window.BAO.utils.getOffsetTop(this.els.header.element)
window.scrollTo({ top: offset, behavior: 'smooth' })
// Distance from the top of the document body
const offset = getOffsetTop(this.els.header)
window.scrollTo({ top: offset, behavior: 'smooth' })
Relative to a specific parent
- 2.0 Build
- 1.0 Build
const container = this.els.container.element
const inner = this.els.inner.element
const offset = window.BAO.utils.getOffsetTop(panel, inner)
const container = this.els.container
const inner = this.els.inner
const offset = getOffsetTop(panel, inner)