🔸.boundingBox
browser ⟩ DOM ⟩ type ⟩ Element ⟩ boxes ⟩ Element+boxes ⟩ .boundingBox
size: (may be fractional)
almost the same as .borderBox size (integer-valued).
"box-sizing: border-box" size = (width, height) -> padding/border included.
👉 compare: .borderBox (a Rect relative to .offsetParent)
💾 Element+boxes, 👉 coordinates
the elements must be in the document to read offsetHeight and other properties, a hidden (display:none) or out of the document element has no size.
inline elements (such as <span>, <code>, <b>)
may span multiple lines and consist of multiple rectangles.
the bounding rect returned by .getBoundingClientRect() will include the entire width/height of these lines.
call .getClientRects() to get individual rectangles of inline elements.
coordinates of document / viewport / container
elem.position() - document coordinates of Element
will change while window scrolling
elem.position() - document coordinates of Element.
💾 replit: elem.getBoundingClientRect()
const { log } = console;
// ⭐️ $all(): select all element
function $all(selector, parent = document) {
return parent.querySelectorAll(selector);
}
// 🔸 elem.showMessageUnder()
Element.prototype.showMessageUnder = function(html, {
timeout = 5,
showRectInfo = true,
}={}) {
// ⭐️ bounding rect
let rect = this.getBoundingClientRect();
log(rect);
// create <div> element
let div = document.createElement('div');
// better to use a css class for the style here (⭐️ don't forget "px"!)
div.style.cssText = `position: fixed; color: red; background: lightyellow; left: ${rect.left}px; top: ${rect.bottom}px; padding: 4px; border: solid black 1px; opacity: 0.7`;
if (showRectInfo) {
html += `<br><code>{x: ${rect.x.toFixed(0)}, y: ${rect.y.toFixed(0)}, width: ${rect.width.toFixed(0)}, height: ${rect.height.toFixed(0)}}</code>`;
}
div.innerHTML = html;
document.body.append(div); // add to the DOM tree
if (timeout > 0) {
setTimeout(() => div.remove(), timeout * 1000); // remove from DOM
}
return div;
};
// click handler
document.onclick = (event) => {
const tag = event.target.tagName;
if (tag !== 'BUTTON') {
log(`clicked on a <${tag}>`); return;
}
$all('span').forEach(span => {
span.showMessageUnder(`bounding rect:`); // 🔸 custom method
});
};Element ⟩
.getClientRects() - individual rectangles of inline elements.
Last updated
Was this helpful?