2

The following code can correctly find the viewport's height, either using plain JavaScript or jQuery, but what if the DOCTYPE is not specified, then both lines that reported something like 410 would now report something like 3016.

Is there a way to find the viewport's height if DOCTYPE is not specified?

<!DOCTYPE html>
<html>
<head>

<style>
    body { height: 3000px; }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

    onload = function() {
        console.log("jQuery version", $.fn.jquery);
        console.log("document.compatMode is", document.compatMode);

        // using jQuery
        console.log("$(window).height() is", $(window).height());

        // using plain JavaScript
        console.log("document.documentElement.clientHeight is", document.documentElement.clientHeight);
    }

</script>

</head>

<body>
    hi
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

3 Answers3

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;
}

Reference : Reference link

Community
  • 1
  • 1
0

To get viewport height:

console.log(window.innerHeight);

Demo

Tested in quirky Chrome and Firefox.


Side note: jQuery does not support quirks mode. Using jQuery on a quirky page (no doctype specificied) may have an unexpected outcome. It is not tested in quirks mode and if it ever breaks, you won't get any support.

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
0

I recently ran into this issue while developing a bookmarklet where I could not control whether or not the DOCTYPE was present. Eventually, I found this post that made my life so much easier!

Here is a simple javascript only function to determine the viewport/window sizing:

function viewport(){
    var e = window, a = 'inner';
    if(!('innerWidth' in window)){
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width  : e[a+'Width'], height : e[a+'Height'] };
}

Usage:

var vp = viewport(),
    h = vp.height,
    w = vp.width;

or

var h = viewport().height,
    w = viewport().width;

We can all thank Andy Langston, whoever he is (;

Jon B
  • 497
  • 1
  • 9
  • 25