Styles, Classes, and Layout via JavaScriptLesson 3.3
How to read element dimensions and position in the browser
getBoundingClientRect, offsetWidth, offsetHeight, scrollTop, scrollLeft, clientHeight, innerWidth, viewport coordinates
Element Dimensions and Position
getBoundingClientRect() returns an object with the element's size and position relative to the viewport. All values are in CSS pixels.
const el = document.querySelector('.tooltip-target');
const rect = el.getBoundingClientRect();
console.log(rect.top); // distance from top of viewport
console.log(rect.left); // distance from left of viewport
console.log(rect.width); // element width
console.log(rect.height); // element heightPositioning a Tooltip
const tooltip = document.querySelector('.tooltip');
tooltip.style.top = (rect.bottom + window.scrollY) + 'px';
tooltip.style.left = (rect.left + window.scrollX) + 'px';Scroll Position
window.scrollY; // pixels scrolled from top
document.body.scrollTop; // older alternative
el.scrollTop; // how far element's own content is scrolledViewport Size
window.innerWidth; // viewport width in px
window.innerHeight; // viewport height in pxoffsetWidth and offsetHeight include border and padding but exclude margin. clientWidth includes padding but excludes border. Prefer getBoundingClientRect for positioning work โ it handles transforms correctly.
