What is the use of document.defaultView property in DOM?
In this Answer, we'll cover the use of the DOM's document.defaultView property. This property retrieves the window object, representing an open window of our browser containing an HTML document.
Syntax
document.defaultView
Here, document refers to the HTML page loaded in our browser.
Return value
The return value of this property is the window object, which can be used to access various methods and properties. In this Answer, we'll look at the innerHeight and innerWidth properties of the window object.
Example
Now let's take a look at a code example that will help us understand how to implement the document.defaultview property:
Explanation
The code example above uses the document.defaultView property to get hold of the window object and is described as follows:
Lines 5–9: In this code snippet, the
<div>tag encapsulates the web page's content. The HTML elements that are necessary to demonstrate the use of the property in the problem statement are as follows:Line 8: This line displays an HTML
<button>listening for theonclickevent and triggers thegetWindowObject()method.
Lines 10–17: These lines of code contain
<script>tags, which enclose ourgetWindowObject()method. The body of the function is made up of the following statements:Line 12: In this line of code, we use the
document.defaultViewproperty assign the return value to the variableviewport.Lines 13–14: Here, we are aware that
viewportnow contains thewindowobject, so we use theviewport.innerHeightandviewport.innerWidthproperties and store the dimensions of the viewport inside the variables,height&width.Line 15: Here, we use a JavaScript
alert()to display the dimensions to the reader.
Note: To read about the
innerHeight&innerWidthproperties of the window object, please refer to this Answer.
Free Resources