UNPKG

@gravityforms/utils

Version:
47 lines (41 loc) 1.48 kB
/** * @module getCoords * @description Get an elements offset relative to viewport for top, left and bottom. Useful for * positioning fixed elements to a set position in the viewport when css position sticky isn't enough. * * @since 1.0.0 * * @param {HTMLElement} element The element to get coordinates for. * * @return {object} An object containing top, left and bottom values for an elements position in viewport. * * @example * import { getCoords } from "@gravityforms/utils"; * * function Example() { * const adminBar = document.getElementById( 'wpadminbar' ); * const barOffset = adminBar ? adminBar.offsetHeight : 0; * const offset = getCoords( exampleHTMLElement ); * * exampleHTMLElement.style.top = `${ offset.top - barOffset }px`; * exampleHTMLElement.style.left = `${ offset.left }px`; * } * */ export default function getCoords( element ) { const box = element.getBoundingClientRect(); const body = document.body; const docEl = document.documentElement; const scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; const scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const top = box.top + scrollTop - clientTop; const left = box.left + scrollLeft - clientLeft; return { top: Math.round( top ), left: Math.round( left ), bottom: Math.round( box.bottom ), }; }