The use of innerHeight and innerWidth properties in JS
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
outerWidthandouterHeightproperties are used. To read more about them, please refer to this Answer.
Syntax
//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.
Return value
Both the properties return a number that represents the height and the width of the window's content area, respectively.
Note: Both
window.innerHeightandwindow.innerWidthproperties are for read-only purposes.
Example
The code example below will depict the use of the properties in our problem statement:
Explanation
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 thewindow.innerWidthandwindow.innerHeightproperties: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 theonclickevent and then fires thegetViewport()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.innerWidthandwindow.innerHeightproperties to retrieve viewport dimensions and assign them to variablesheightandwidth, respectively.Lines 15‒16: We fetch the placeholder
<p>tag using thedocument.getElementById()method and use theinnerHTMLproperty to render the window dimensions, as seen in the output tab.
Note: To read more on
document.getElementById()method and theinnerHTMLproperty, please visit the links below:
Free Resources