Get the height and width of the browser viewport without scrollbars using jquery?
How do I get the height and width of the browser viewport without scrollbars using jQuery?
Here is what I have tried so far:
var viewportWidth = $("body").innerWidth();
var viewportHeight = $("body").innerHeight();
This solution does not take into account the browser scrollbars.
Solution 1:
$(window).height();
$(window).width();
More info
- http://api.jquery.com/height/
- http://api.jquery.com/width/
Using jQuery is not essential for getting those values, however. Use
document.documentElement.clientHeight;
document.documentElement.clientWidth;
to get sizes excluding scrollbars, or
window.innerHeight;
window.innerWidth;
to get the whole viewport, including scrollbars.
document.documentElement.clientHeight <= window.innerHeight; // is always true
Solution 2:
Don't use jQuery, just use javascript for correct result:
This includes scrollbar width/height:
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
alert('viewport width is: '+ windowWidth + ' and viewport height is:' + windowHeight);
This excludes scrollbar width/height:
var widthWithoutScrollbar = document.body.clientWidth;
var heightWithoutScrollbar = document.body.clientHeight;
alert('viewport width is: '+ widthWithoutScrollbar + ' and viewport height is:' + heightWithoutScrollbar);
Solution 3:
Here is a generic JS which should work in most browsers (FF, Cr, IE6+):
var viewportHeight;
var viewportWidth;
if (document.compatMode === 'BackCompat') {
viewportHeight = document.body.clientHeight;
viewportWidth = document.body.clientWidth;
} else {
viewportHeight = document.documentElement.clientHeight;
viewportWidth = document.documentElement.clientWidth;
}
Solution 4:
You're using the wrong method calls. A viewport is the "window" that's open on the document: how much of it you can see and where.
Using $(window).height()
will not give you the viewport size it will give you the size of the entire window, which is usually the size of the entire document though the document could be even larger.
To get the size of the actual viewport use window.innerHeight
and window.innerWidth
.
https://gist.github.com/bohman/1351439
Do not use the jQuery methods, e.g. $(window).innerHeight()
, as these give the wrong numbers. They give you the window's height, not innerHeight
.
Solution 5:
Description
The following will give you the size of the browsers viewport.
Sample
$(window).height(); // returns height of browser viewport
$(window).width(); // returns width of browser viewport
More Information
- jQuery.height()
- jQUery.width()