Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get document height and width without using jquery

Tags:

javascript

People also ask

How do you find the height of a document?

To get the height of a document, we can get the max of the scrollHeight , offsetHeight , or clientHeight properties. The document can be stored in the document. body or document. documentElement properties depending on the browser used.

How do you measure the width and height of a viewport?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.


var height = document.body.clientHeight;
var width = document.body.clientWidth;

Check: this article for better explanation.


Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):

Math.max(
    document.documentElement["clientWidth"],
    document.body["scrollWidth"],
    document.documentElement["scrollWidth"],
    document.body["offsetWidth"],
    document.documentElement["offsetWidth"]
);

just replace Width for "Height" to get Height.


This is a cross-browser solution:

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

You should use getBoundingClientRect as it usually works cross browser and gives you sub-pixel precision on the bounds rectangle.

elem.getBoundingClientRect()

Get document size without jQuery

document.documentElement.clientWidth
document.documentElement.clientHeight

And use this if you need Screen size

screen.width
screen.height

This should work for all browsers/devices:

function getActualWidth()
{
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}