Skip to content

Instantly share code, notes, and snippets.

@rspieker
Last active March 19, 2016 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rspieker/6859da3d3c5dd259f203 to your computer and use it in GitHub Desktop.
Save rspieker/6859da3d3c5dd259f203 to your computer and use it in GitHub Desktop.
Obtain screen/window/document dimensions
/**
* Obtain screen/window/document(.documentElement)/element dimensions
* @param object target
* @param mixed prefix [optional, default false-ish - no prefix, use best for target]
* @note best:
* - window >> outer
* - document >> client|offset|scroll
* - element >> client|offset|scroll
*/
function dimension(target, prefix) {
var prop = function(name, fix) {
return (!(fix && fix.length) ? [name] : [].concat(fix))
.map(function(p) {
return (target ? target[p && fix ? p + name[0].toUpperCase() + name.substr(1) : name] : null) || 0;
});
};
target = target === document ? document.documentElement : target;
prefix = prefix || (target && 'nodeType' in target ? ['client', 'offset', 'scroll'] : (target === window ? 'outer' : null));
return [
Math.max.apply(Math, prop('width', prefix)),
Math.max.apply(Math, prop('height', prefix))
].join('/');
}
dimension(screen); // <width>/<height>
dimension(screen, 'avail'); // <availWidth>/<availHeight>
dimension(window); // <outerWidth>/<outerHeight>
dimension(window, 'inner'); // <innerWidth>/<innerHeight>
dimension(document); // <max clientWidth|offsetWidth|scrollWidth>/<max clientHeight|offsetHeight|scrollHeight>
// document as target will actually use document.documentElement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment