Skip to content

Instantly share code, notes, and snippets.

@alxrocha
Created July 14, 2012 13:37
Show Gist options
  • Save alxrocha/3111390 to your computer and use it in GitHub Desktop.
Save alxrocha/3111390 to your computer and use it in GitHub Desktop.
(function (exports) {
var supportsGCS = "defaultView" in exports.document && "getComputedStyle" in exports.document.defaultView;
function getStyle(element, property) {
// `element.ownerDocument` returns the used style values relative to the
// element's parent document (which may be another frame). `defaultView`
// is required for Safari 2 support and when retrieving framed styles in
// Firefox 3.6 (https://github.com/jquery/jquery/pull/524#issuecomment-2241183).
var style = supportsGCS ? element.ownerDocument.defaultView.getComputedStyle(element, null) : element.currentStyle;
return (style || element.style)[property];
}
// Note that `element` *must* be visible and in the document; otherwise,
// `offsetWidth` and `offsetHeight` will be `0`.`
exports.getContentDimensions = getContentDimensions;
function getContentDimensions(element) {
// The `offsetWidth` and `offsetHeight` properties respectively return the
// border edge width and height (see the W3C CSSOM View Module, section
// 7.1): content {width, height} + padding {width, height} + border
// {width, height} (CSS box model).
var width = element.offsetWidth, height = element.offsetHeight;
// Subtract the padding and border values from the width and height to
// obtain the content dimensions. `parseFloat` converts the pixel values to
// numbers. The properties must be accessed separately because
// `getComputedStyle` returns empty values for shorthand properties.
var contentWidth = width - parseFloat(getStyle(element, "borderLeftWidth")) || 0 - parseFloat(getStyle(element, "borderRightWidth")) || 0 - parseFloat(getStyle(element, "paddingLeft")) || 0 - parseFloat(getStyle(element, "paddingRight")) || 0;
var contentHeight = height - parseFloat(getStyle(element, "borderTopWidth")) || 0 - parseFloat(getStyle(element, "borderBottomWidth")) || 0 - parseFloat(getStyle(element, "paddingTop")) || 0 - parseFloat(getStyle(element, "paddingBottom")) || 0;
return {
"width": contentWidth,
"height": contentHeight
};
}
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment