Skip to content

Instantly share code, notes, and snippets.

@schorfES
Last active May 23, 2018 19:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schorfES/d55f5390307f33167834 to your computer and use it in GitHub Desktop.
Save schorfES/d55f5390307f33167834 to your computer and use it in GitHub Desktop.
Calculate the bounding box of a DOM element with jQuery
/**
* Calculate the bounding box of a DOM element.
*
* @param element is the jQuery element which is the root of the calculation
*/
function getBoundingBox(element) {
var
position = element.offset(),
width = element.outerWidth(),
height = element.outerHeight(),
box = {
xMin: position.left,
xMax: position.left + width,
yMin: position.top,
yMax: position.top + height
}
;
// Ignore elements with overflow hidden, children will be masked and
// can be ignored...
if (element.css('overflow') !== 'hidden') {
element.children().each(function() {
var
child = $(this),
childBox = getBoundingBox(child)
;
// Merge child box into current box:
box = {
xMin: Math.min(box.xMin, childBox.xMin),
xMax: Math.max(box.xMax, childBox.xMax),
yMin: Math.min(box.yMin, childBox.yMin),
yMax: Math.max(box.yMax, childBox.yMax)
};
});
}
return box;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment