I have a conatiner div with a set height and width positioned relatively. I'd like to figure out in Javascript by how much, if any, it's children extend beyond the container div's edge in the top, right, bottom and left directions. Any help would be much appreciated!
2 Answers
Here's the code for top:
var myDivEl = document.getElementById("my-div");
var divTop = myDivEl.getBoundingClientRect().top;
var descendants = myDivEl.getElementsByTagName("*");
var tops = [];
for (var i = 0, descendant; descendant = descendants[i]; ++i) {
tops.push(descendant.getBoundingClientRect().top);
}
var minTop = Math.min.apply(Math, tops);
var diff = divTop - minTop;
More generally:
function getBoundingClientRectDiff(el, propName, minOrMax) {
var propValue = el.getBoundingClientRect()[propName];
var descendants = myDivEl.getElementsByTagName("*");
var descendantPropValues = [];
for (var i = 0, descendant; descendant = descendants[i]; ++i) {
descendantPropValues.push(descendant.getBoundingClientRect()[propName]);
}
var extremePropValue = Math[minOrMax].apply(Math, descendantPropValues);
return minOrMax === "Max" ? extremePropValue - propValue
: propValue - extremePropValue;
}
function getBoundingClientRectDiffs(el) {
return {
top: getBoundingClientRectDiff(el, "top", "Min"),
right: getBoundingClientRectDiff(el, "right", "Max"),
bottom: getBoundingClientRectDiff(el, "bottom", "Max"),
left: getBoundingClientRectDiff(el, "left", "Min")
};
}
// use like so:
var diffs = getBoundingClientRectDiffs(myDivEl);
console.log(diffs.top, diffs.right, diffs.bottom, diffs.left);
2 Comments
VinnyD
Domenic, how can I adapt this to take into account the display property of child nodes? Basically, if a child is set to display:none; i'd like to not include it or any of it's child nodes in the calculation.
Domenic
@VinnyD, you would add an
if(descendant.style.display !== "none") { } inside the for loop, wrapping descendantPropValues.push(...).