I'm trying to find the exact height and width of a browser's viewport, but I suspect that either Mozilla or IE is giving me the wrong number. Here's my method for height:
var viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
I haven't started on width yet but I'm guessing it's going to be something similar.
Is there a more correct way of getting this information? Ideally, I'd like the solution to work with Safari/Chrome/other browsers as well.
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
Use window. innerWidth and window. innerHeight to get the current screen size of a page.
Getting viewport height To detect interior height of the window in pixels we can use innerHeight property. window. innerHeight returns height of window including the scrollbar. To exclude scrollbar we need to use the root <html> element's clientHeight property instead.
A simple way to solve this is to use the viewport percentage unit vh instead of %. One vh is defined as being equal to 1% of a viewport's height. As such, if you want to specify that something is 100% of the latter, use " height: 100vh ". Or if you want to make it half the height of the viewport, say " height: 50vh ".
You might try this:
function getViewport() { var viewPortWidth; var viewPortHeight; // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight if (typeof window.innerWidth != 'undefined') { viewPortWidth = window.innerWidth, viewPortHeight = window.innerHeight } // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { viewPortWidth = document.documentElement.clientWidth, viewPortHeight = document.documentElement.clientHeight } // older versions of IE else { viewPortWidth = document.getElementsByTagName('body')[0].clientWidth, viewPortHeight = document.getElementsByTagName('body')[0].clientHeight } return [viewPortWidth, viewPortHeight]; }
( http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ )
However, it is not even possible to get the viewport information in all browsers (e.g. IE6 in quirks mode). But the above script should do a good job :-)
You may use shorter version:
<script type="text/javascript"> <!-- function getViewportSize(){ var e = window; var a = 'inner'; if (!('innerWidth' in window)){ a = 'client'; e = document.documentElement || document.body; } return { width : e[ a+'Width' ] , height : e[ a+'Height' ] } } //--> </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With