JAVASCRIPT

Get Element's Position and Dimensions with getBoundingClientRect

Accurately retrieve an element's size and position relative to the viewport using JavaScript's `getBoundingClientRect()` method for precise layout control.

const targetElement = document.getElementById('targetBox');
const infoDiv = document.getElementById('infoDisplay');

function updateElementInfo() {
  const rect = targetElement.getBoundingClientRect();

  let info = `
    <strong>Element Position and Dimensions:</strong><br>
    Left: ${rect.left.toFixed(2)}px (distance from viewport left)<br>
    Top: ${rect.top.toFixed(2)}px (distance from viewport top)<br>
    Right: ${rect.right.toFixed(2)}px (distance from viewport right)<br>
    Bottom: ${rect.bottom.toFixed(2)}px (distance from viewport bottom)<br>
    Width: ${rect.width.toFixed(2)}px<br>
    Height: ${rect.height.toFixed(2)}px<br>
    X (same as left): ${rect.x.toFixed(2)}px<br>
    Y (same as top): ${rect.y.toFixed(2)}px
  `;

  infoDiv.innerHTML = info;
}

// Initial display
updateElementInfo();

// Update info on scroll and resize
window.addEventListener('scroll', updateElementInfo);
window.addEventListener('resize', updateElementInfo);

// Setup target element for demonstration
targetElement.style.width = '150px';
targetElement.style.height = '100px';
targetElement.style.backgroundColor = 'coral';
targetElement.style.margin = '200px'; // To make it scrollable
targetElement.style.border = '2px solid #333';
targetElement.textContent = 'Scroll and Resize Me!';
targetElement.style.textAlign = 'center';
targetElement.style.lineHeight = '100px';
targetElement.style.color = 'white';

// Setup info display element
infoDiv.style.border = '1px solid gray';
infoDiv.style.padding = '10px';
infoDiv.style.backgroundColor = '#f4f4f4';
infoDiv.style.fontFamily = 'monospace';
infoDiv.style.marginTop = '20px';

// Add some extra content to make the page scrollable
const dummyContent = document.createElement('div');
dummyContent.style.height = '1000px';
dummyContent.style.backgroundColor = '#fafafa';
dummyContent.textContent = 'Scroll down to see the effect!';
document.body.appendChild(dummyContent);
How it works: The `getBoundingClientRect()` method returns a `DOMRect` object providing the size of an element and its position relative to the viewport. It contains properties like `left`, `top`, `right`, `bottom`, `width`, and `height`. These values dynamically update as the user scrolls or resizes the window, making it invaluable for precisely positioning elements, creating tooltips, implementing scroll-based animations, or checking for element visibility within the current view.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs