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:
Example
Try this code »<script>
function windowSize(){
let w = window.innerWidth;
let 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:
Example
Try this code »<script>
function windowSize(){
let w = document.documentElement.clientWidth;
let h = document.documentElement.clientHeight;
alert("Width: " + w + ", " + "Height: " + h);
}
</script>
<button type="button" onclick="windowSize();">Get Window Size</button>