JAVASCRIPT
Get Element Dimensions and Position (getBoundingClientRect)
Precisely retrieve the size and position of any DOM element relative to the viewport using `getBoundingClientRect()`, essential for dynamic layouts, overlays, and animations.
function getElementRect(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return null;
}
const rect = element.getBoundingClientRect();
console.log(`Rectangle for #${elementId}:`);
console.log(` Top: ${rect.top}px`);
console.log(` Right: ${rect.right}px`);
console.log(` Bottom: ${rect.bottom}px`);
console.log(` Left: ${rect.left}px`);
console.log(` Width: ${rect.width}px`);
console.log(` Height: ${rect.height}px`);
// Calculate center coordinates (relative to viewport)
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
console.log(` Center X: ${centerX}px`);
console.log(` Center Y: ${centerY}px`);
return rect;
}
// Example usage:
document.addEventListener('DOMContentLoaded', () => {
const myBox = document.createElement('div');
myBox.id = 'myBox';
myBox.style.width = '150px';
myBox.style.height = '100px';
myBox.style.backgroundColor = 'coral';
myBox.style.margin = '20px';
myBox.style.position = 'absolute';
myBox.style.top = '50px';
myBox.style.left = '70px';
document.body.appendChild(myBox);
getElementRect('myBox');
// You can also call it on other elements or on window resize/scroll
window.addEventListener('resize', () => {
console.log('Window resized, re-calculating rect:');
getElementRect('myBox');
});
});
How it works: The `getBoundingClientRect()` method returns a `DOMRect` object providing the size of an element and its position relative to the viewport. It includes properties like `top`, `right`, `bottom`, `left`, `width`, and `height`, which are crucial for precise positioning, collision detection, and responsive UI adjustments.