Last active
May 23, 2018 19:02
-
-
Save schorfES/d55f5390307f33167834 to your computer and use it in GitHub Desktop.
Calculate the bounding box of a DOM element with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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