Last active
December 15, 2015 23:49
-
-
Save ahsquared/5343289 to your computer and use it in GitHub Desktop.
js to accurately find width and height of document
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
function docElem(property) { | |
var t; | |
return ((t = document.documentElement) || (t = document.body.parentNode)) && t[property] ? t : document.body; | |
} | |
// View width and height excluding any visible scrollbars | |
// http://www.highdots.com/forums/javascript/faq-topic-how-do-i-296669.html | |
// 1) document.client[Width|Height] always reliable when available, including Safari2 | |
// 2) document.documentElement.client[Width|Height] reliable in standards mode DOCTYPE, except for Safari2, Opera<9.5 | |
// 3) document.body.client[Width|Height] is gives correct result when #2 does not, except for Safari2 | |
// 4) When document.documentElement.client[Width|Height] is unreliable, it will be size of <html> element either greater or less than desired view size | |
// https://bugzilla.mozilla.org/show_bug.cgi?id=156388#c7 | |
// 5) When document.body.client[Width|Height] is unreliable, it will be size of <body> element less than desired view size | |
function viewSize() { | |
// This algorithm avoids creating test page to determine if document.documentElement.client[Width|Height] is greater then view size, | |
// will succeed where such test page wouldn't detect dynamic unreliability, | |
// and will only fail in the case the right or bottom edge is within the width of a scrollbar from edge of the viewport that has visible scrollbar(s). | |
var doc = docElem('clientWidth'), | |
body = document.body, | |
w, h; | |
return document.clientWidth ? { w: document.clientWidth, h: document.clientHeight} : | |
doc === body | |
|| (w = Math.max(doc.clientWidth, body.clientWidth)) > self.innerWidth | |
|| (h = Math.max(doc.clientHeight, body.clientHeight)) > self.innerHeight ? { w: body.clientWidth, h: body.clientHeight} : | |
{ w: w, h: h }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment