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 recall from earlier sections, we've used the alert()
method in our scripts to display popup messages. This method belongs to the window
object.
In the upcoming chapters, we will explore several new methods and properties of the window
object that allow us to prompt users for information, confirm their actions, open new windows, and more. These features enhance the interactivity of your web pages.
The window
object provides the innerWidth
and innerHeight
properties to determine the dimensions of the browser window's viewport (in pixels), including any visible scrollbars. Here's an example that shows the current size of the window when a button is clicked:
<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 wish to determine the width and height of the window excluding the scrollbars, you can utilize the clientWidth
and clientHeight
properties of any DOM element (such as a div
), as shown below:
<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 refers to the root element of the document, which is the <html>
element. On the other hand, the document.body
object represents the <body>
element. Both are supported in all major browsers.