JS Window

Welcome to another tutorial, here you will learn about the JavaScript window object.

 

The Window Object

A window containing a DOM document is represented by the window object. A window may be the main window, a frameset or single frame, or even a new window created with JavaScript

In our previous tutorial, we used the alert() method in our scripts to show popup messages. The alert() is a method for the window object.

In subsequent tutorials, you learn some new methods and properties of the window object that enables us to do things such as prompt the user for information, open new windows, confirm the user's action, and so on. They will let you add more interactivity to your web pages.

 

Calculating Width and Height of the Window

The window object provides the innerWidth and innerHeight property used in finding the width and height of the browser window viewport (in pixels) including the horizontal and vertical scrollbar if rendered. Below is an example that displays the current size of the window.

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

Try with example

 

However, 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>

Try with example

 

Note: The root element of the document is represented by the ‘document.documentElement’ object, which is the <html> element, whereas the ‘document.body’ object represents the <body> element. The both of them are supported in all major browsers.