JAVASCRIPT BASIC
JAVASCRIPT & DOM
JAVASCRIPT & BOM
JAVASCRIPT ADVANCED
JAVASCRIPT EXAMPLES
JAVASCRIPT REFERENCE

JavaScript Window

In this tutorial you will learn about the JavaScript window object.

The Window Object

The window object represents a window containing a DOM document. A window can be the main window, a frame set or individual frame, or even a new window created with JavaScript.

If you remember from the preceding chapters we've used the alert() method in our scripts to show popup messages. This is a method of the window object.

In the next few chapters we will see a number of new methods and properties of the window object that enables us to do things such as prompt user for information, confirm user's action, open new windows, etc. which lets you to add more interactivity to your web pages.


Calculating Width and Height of the Window

The window object provides the innerWidth and innerHeight property to find out the width and height of the browser window viewport (in pixels) including the horizontal and vertical scrollbar, if rendered. Here's is an example that displays the current size of the window on button click:

<script>
function windowSize(){
    var w = window.innerWidth;
    var h = window.innerHeight;
    alert("Width: " + w + ", " + "Height: " + h);
}
</script>
 
<button type="button" onclick="windowSize();">Get Window Size</button>

However, if you want to find out the width and height of the window excluding the scrollbars you can use the clientWidth and clientHeight property of any DOM element (like a div), as follow:

<script>
function windowSize(){
    var w = document.documentElement.clientWidth;
    var h = document.documentElement.clientHeight;
    alert("Width: " + w + ", " + "Height: " + h);
}
</script>
 
<button type="button" onclick="windowSize();">Get Window Size</button>

Note: The document.documentElement object represents the root element of the document, which is the <html> element, whereas the document.body object represents the <body> element. Both are supported in all major browsers.

Your Feedback:

We would love to hear from you, please drop us a line.