XIMRX
XIMRX

Reputation: 2172

How to get viewport height of screen of browser?

All questions I see answer:

$(window).height();

But this returns not the size of viewport but size of page, for example if I style <body> to height 1000px this will return 1000 but not the size of view port. I need size of viewport not the collective page size that is scroll able.

Upvotes: 0

Views: 2448

Answers (4)

Arnaud Leyder
Arnaud Leyder

Reputation: 7002

$(window).height();

should return the height of the viewport (even if you set the height of the body tag in pixels). I also use:

var heightViewport = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

which has given me better accuracy on iOS especially.

$(document).height();

should return the height of the document (hence the height of the body tag in your case).

Are your sure you are not using document instead of window?

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11869

try this:

var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0];
var x=w.innerWidth||e.clientWidth||g.clientWidth;
var y=w.innerHeight||e.clientHeight||g.clientHeight;
    console.log(x,y);

main source:http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript

Upvotes: 0

Makaze
Makaze

Reputation: 1086

It will return the size of the viewport.

$('#viewportDimensions').text($(window).width() + ', ' + $(window).height());

$(window).resize(function() {
  $('#viewportDimensions').text($(window).width() + ', ' + $(window).height());
});

resize page in fiddle

Upvotes: 0

sagar43
sagar43

Reputation: 3464

You can try

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
if(window.innerWidth !== undefined && window.innerHeight !== undefined) {
var w=window.innerWidth;
var h=window.innerHeight;
} else {
var w=document.documentElement.clientWidth;
var h=document.documentElement.clientHeight;
}
var txt="Page size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML=txt;
}
</script>
<body onresize="myFunction()" onload="myFunction()">
<p>
Try to resize the page.
</p>
<p id="demo">
&nbsp;
</p>
</body>
</html>

Upvotes: 2

Related Questions