getBoundingClientRect() and getComputedStyle() with scroll-aware page coordinates, padding values as numbers, and Shadow DOM support.import position from '@pim.sk/utils/position.mjs'
Returns position and size of an element using getBoundingClientRect(). Accepts a CSS selector string or a DOM element directly. Also searches inside Shadow DOM.
const p = new position( ".my-el" ) // CSS selector
const p = new position( domEl ) // DOM element directly
p.top // distance from viewport top (changes on scroll)
p.left // distance from viewport left
p.bottom // distance from viewport bottom
p.right // distance from viewport right
p.width // element width
p.height // element height
Target element
const p = new position( ".pos-basic-target" )
p.top // → e.g. 320
p.left // → e.g. 24
p.width // → e.g. 680
p.height // → e.g. 48
top / left are relative to the current viewport (change when scrolling). topp / leftp are absolute positions from the page top — scroll offset is added. Same relationship for x/xp and y/yp.
p.top // distance from viewport top — changes on scroll
p.topp // distance from page top — fixed, scroll-independent
p.left // distance from viewport left
p.leftp // distance from page left
// formula:
// topp = top + window.scrollY
// leftp = left + window.scrollX
Target element — scroll the page and click again to see top change, topp stay fixed
const p = new position( ".pos-page-target" )
p.top // viewport-relative → changes on scroll
p.topp // page-absolute → fixed
// topp = top + scrollY (' . 'Math.round(p.topp) === Math.round(p.top + window.scrollY)' . ')
Returns computed padding values as plain numbers (px stripped). Useful when calculating inner content area without having to parse CSS strings manually.
p.padtop // computed padding-top as number
p.padbottom // computed padding-bottom as number
p.padleft // computed padding-left as number
p.padright // computed padding-right as number
// inner content width:
const innerW = p.width - p.padleft - p.padright
Target — padding: 12px 24px 8px 32px
const p = new position( ".pos-pad-target" )
p.padtop // → 12
p.padright // → 24
p.padbottom // → 8
p.padleft // → 32
const innerW = p.width - p.padleft - p.padright
The .get getter returns the entire position instance. Use when you need all values at once or want to pass the position object elsewhere.
const p = new position( ".my-el" )
p.get // → position instance (all getters)
p.get.top // → same as p.top
p.get.width // → same as p.width
// log everything at once:
console.log( p.get )
Target element
const p = new position( ".pos-get-target" )
console.log( p.get )
// or destructure what you need:
const { top, left, width, height } = p.get