- Published
- Author
- Syed SibtainSystem Analyst
getBoundingClientRect() A crucial DOM method that gives us an element's position and size relative to the viewport, not the document.Example:
JavaScript
const rect = container.getBoundingClientRect();What
getBoundingClientRect() returns?Code
{
top: 100, // Distance from viewport top to element top
left: 200, // Distance from viewport left to element left
right: 400, // Distance from viewport left to element right
bottom: 300, // Distance from viewport top to element bottom
width: 200, // Element width
height: 200, // Element height
x: 200, // Same as left (for compatibility)
y: 100 // Same as top (for compatibility)
}Real Usage Example: Image Comparison Slider:
Code
// User drags the slider to compare two images
handleDrag(event) {
const container = this.getContainer(); // The image container
const rect = container.getBoundingClientRect();
// Convert global mouse position to slider position
const x = event.clientX - rect.left; // Mouse X relative to container
const percentage = this.calculatePercentage(x, rect.width);
// Update slider position (0-100%)
this.sliderPosition = percentage;
this.updateSliderPosition(percentage);
}Step-by-Step Breakdown:
1. User drags mouse → event.clientX = 350 (global position)
2. Get container bounds → rect.left = 200 (container starts at 200px from viewport left)
3. Calculate relative position → 350 - 200 = 150px (mouse is 150px from container's left edge)
4. Convert to percentage → 150 / 400 = 37.5% (150px out of 400px container width)
5. Update slider → Move slider to 37.5% position
getBoundingClientRect() is the bridge between global coordinates and element-relative coordinates.#CCT1JMA0Z #stimulus