1

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 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@VinnyD, you would add an if(descendant.style.display !== "none") { } inside the for loop, wrapping descendantPropValues.push(...).
0

You could also get the difference between an element's width and scrollWidth or height and scrollHeight properties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.