Why is $ (window) .height () so wrong?

I am trying to get the current height of the browser viewport using

$(window).on('resize',function() { console.log("new height is: "+$(window).height()); }); 

But I get values ​​that are too low. When the viewport is about 850px high, I get values ​​of about 350 or 400 pixels from a height (). What?

Example: http://jsfiddle.net/forgetcolor/SVqx9/

+18
jquery
May 13 '12 at 4:25
source share
6 answers

One possible reason may be that you are checking the console with firebug / something else. So you won’t get the correct window height due to the height of Firebug.

You can try something like this:

take the span / div document in the document:

 <span id="res"></span> 

and then

 $(window).on('resize',function() { $('#res').html("new height is: "+$(window).height()); }); 

Or, if you want to check, put on the firebug console, then separate it from the browser and then check the result.

+10
May 13, '12 at 4:32
source share

I had the same problem in Firefox, but I added <!DOCTYPE HTML> to my index and it worked.

Source: http://viralpatel.net/blogs/jquery-window-height-incorrect/

+44
Sep 22 '14 at 17:14
source share

For those who still have problems after the above solutions ...

Please check your browser browsing ratio on your project.html ..

The value of $ (window) .height () does not coincide with the "real" pixels of the client area when the view relation changes! (and therefore the other $ (xx) .width () ... in this situation)

(The browser remembered my careless 110% ratio, tuned days ago ...)

+4
Dec 24 '15 at 7:19
source share

No play. Keep in mind that window height is reduced by using elements in the Chrome browser, such as the address bar, developer tools, bookmark toolbars, and more. The following displays the exact height of the viewport:

jsbin will give you a pretty good estimate of the window height, since it does not limit your code output to a small iframe, like other js testing sites like jsfiddle.

http://jsbin.com/otaqej/edit#javascript,html

 <!DOCTYPE html> <html> <head> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.js"></script> </head> <body> <div id="message">Height: 0</div> <script> $(window).on("resize", function(){ $("#message").html( "Height: " + $(window).height() ); }); </script> </body> </html> 
+2
May 13 '12 at 4:38
source share

JSFiddle works by creating an <iframe> that dynamically loads after the code is rendered.

Your JavaScript calculates the height of the window, which is the height of the <iframe> , which for me is about 400 pixels.

Your code does what it should be.

+2
May 13 '12 at 4:38
source share

I saw jQuery $(window).height() return the wrong value on a Chrome mobile phone, although my viewport and DOCTYPE declarations were in place. In the end, I used window.innerHeight .

0
Jun 12 '19 at 12:07 on
source share



All Articles