In this Answer, we'll look at the innerWidth
and innerHeight
properties of the window
object. These properties return the width & height of the
Note: To get the width & height inclusive of the toolbars and scrollbars, the
outerWidth
andouterHeight
properties are used. To read more about them, please refer to this Answer.
//returns the width of the window in pixels
window.innerWidth
//returns the height of the window in pixels
window.innerHeight
Here, the window
object is an opened window of our browser.
Both the properties return a number that represents the height and the width of the window's content area, respectively.
Note: Both
window.innerHeight
andwindow.innerWidth
properties are for read-only purposes.
The code example below will depict the use of the properties in our problem statement:
The description of the code in the widget above is as follows:
Lines 5–10: This piece of code contains a <div>
tag that encloses the content of our web page. The HTML elements help us demonstrate the functionality of the window.innerWidth
and window.innerHeight
properties:
Line 8: Here, we have a placeholder <p>
tag, which gets populated by the viewport size when the user clicks on the button present on line 9.
Line 9: This line displays a <button>
tag listening for the onclick
event and then fires the getViewport()
method.
Lines 11–18: In these lines of code, we define the getViewport()
method, whose body is composed of the following instructions:
Lines 13–14: In these lines, we use the window.innerWidth
and window.innerHeight
properties to retrieve viewport dimensions and assign them to variables height
and width
, respectively.
Lines 15‒16: We fetch the placeholder <p>
tag using the document.getElementById()
method and use the innerHTML
property to render the window dimensions, as seen in the output tab.
Note: To read more on
document.getElementById()
method and theinnerHTML
property, please visit the links below:
Free Resources