Last active
December 23, 2015 13:49
-
-
Save tremby/6644465 to your computer and use it in GitHub Desktop.
Jquery plugins to provide recursive bounds, height and width calculators for elements
This file contains hidden or 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
# Get the bounds of elements including all children relative to the document | |
# - The visibility property is totally ignored whether visible or hidden | |
# - Elements with display: none are skipped | |
# - Horizontal bounds of children are ignored when overflow-x is hidden | |
# - Vertical bounds of children are ignored when overflow-y is hidden | |
$.fn.getBounds = -> | |
bounds = | |
left: Infinity | |
right: -Infinity | |
top: Infinity | |
bottom: -Infinity | |
@each -> | |
$el = $ @ | |
return true if $el.css('display') is 'none' | |
offset = $el.offset() | |
bounds.left = Math.min bounds.left, offset.left | |
bounds.top = Math.min bounds.top, offset.top | |
bounds.right = Math.max bounds.right, offset.left + $el.outerWidth() | |
bounds.bottom = Math.max bounds.bottom, offset.top + $el.outerHeight() | |
overflowX = $el.css('overflow-x') is 'visible' | |
overflowY = $el.css('overflow-y') is 'visible' | |
if overflowX or overflowY | |
childrenBounds = $el.children().getBounds() | |
if overflowX and childrenBounds? | |
bounds.left = Math.min bounds.left, childrenBounds.left | |
bounds.right = Math.max bounds.right, childrenBounds.right | |
if overflowY and childrenBounds? | |
bounds.top = Math.min bounds.top, childrenBounds.top | |
bounds.bottom = Math.max bounds.bottom, childrenBounds.bottom | |
if bounds.left is Infinity or bounds.right is -Infinity \ | |
or bounds.top is Infinity or bounds.bottom is -Infinity | |
return null | |
return bounds | |
# using getBounds, recursively get the total width of an element and its | |
# children | |
$.fn.totalWidth = -> | |
bounds = @getBounds() | |
return bounds.right - bounds.left | |
# using getBounds, recursively get the total height of an element and its | |
# children | |
$.fn.totalHeight = -> | |
bounds = @getBounds() | |
return bounds.bottom - bounds.top |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment