Reputation: 3931
I'm trying to get the total height of a page using JavaScript so I can check if the page is long enough to display something, however in my testing I am unable to get the total height of a page.
I've looked around on the Internet but things like this don't seem to be well documented, as all I can find is scrollHeight
, which, as I might mention, doesn't work.
Any way to use JavaScript to find it?
Upvotes: 26
Views: 62721
Reputation: 82483
Height of entire page...
document.body.offsetHeight
Height of viewport...
var h,
de = document.documentElement;
if (self.innerHeight) {h = window.innerHeight;}
else if (de && de.clientHeight) {h = de.clientHeight;}
else if (document.body) {h = document.body.clientHeight;}
This article may help you.
Upvotes: 3
Reputation: 7631
To find the height of the entire document you could just find the highest DOM Node on current page with a simple recursion:
;(function() {
var pageHeight = 0;
function findHighestNode(nodesList) {
for (var i = nodesList.length - 1; i >= 0; i--) {
if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
pageHeight = Math.max(elHeight, pageHeight);
}
if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
}
}
findHighestNode(document.documentElement.childNodes);
// The entire page height is found
console.log('Page height is', pageHeight);
})();
NOTE: It is working with Iframes
.
Enjoy!
Upvotes: 2
Reputation: 19129
document.documentElement.scrollHeight
is working ok for me in the latest version of Internet Explorer, Chrome, Firefox and Safari.
Upvotes: 19
Reputation: 127
Perhaps use the position of an element at the bottom of the page, like:
$("#footer").offset().top
Upvotes: 1
Reputation: 107950
Without a framework:
var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
Upvotes: 47
Reputation: 104178
Have a look at the documentation. One of the supported methods: height, innerHeight, outerHeight may be suitable for you.
Upvotes: 0