Skip to main content

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:

ArgumentTypeDefaultDescription
elHTMLElementThe element you want the offset for.
parentHTMLElementdocument.bodyThe ancestor you want the offset measured relative to.
offsetTopnumber0The starting value. This is used internally by the recursion — leave it as-is.

Usage examples

Basic

// Distance from the top of the document body
const offset = window.BAO.utils.getOffsetTop(this.els.header.element)

window.scrollTo({ top: offset, behavior: 'smooth' })

Relative to a specific parent

const container = this.els.container.element
const inner = this.els.inner.element

const offset = window.BAO.utils.getOffsetTop(panel, inner)