Home »
JavaScript
JavaScript Window Object
JavaScript | Window Object: In this program, we are going to learn about the Window object with its properties, methods with examples.
Submitted by Siddhant Verma, on September 01, 2021
What if I tell you that whatever raw, pure vanilla JS you have been using up till now to make simple applications has something missing? And I haven't even seen what you have been doing till now.
We have used various methods in JavaScript right from the beginning. Most of your hello world applications started with a simple alert() function. Or while learning asynchronous code you used the functions setInterval() and setTimeout() a couple of times. All these functions are actually methods, not functions. Recall that the difference between a function and a method is that a method is a function invoked on an object. But where is the object? We have been using these methods without using any parent object for their invocation. Well, the truth is, there is an underlying object which invokes all these methods that is the window object.
The window object is built onto the browser and every function that we normally use is built on this window object. It is the global object in JavaScript or the mother of all objects. We have extensively talked about the window object when we were learning the scope of this object in JavaScript. Have a quick read on that article here: JavaScript this Object.
Everything we do on the frontend is stored on this window object.
Hence all these functions are simply methods of this window object.
Let's look at a few examples-
Window Object
window;
Output:
Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
$: ƒ $(id)
Iframe: ƒ (a,b,c,d,e,f,g)
IframeBase: ƒ (a,b,c,d,e,f,g,k)
IframeProxy: ƒ (a,b,c,d,e,f,g)
IframeWindow: ƒ (a,b,c,d,e,f,g)
LocalNTP: ƒ LocalNTP()
ToolbarApi: ƒ ()
alert: ƒ alert()
applicationCache: ApplicationCache {status: 0, oncached: null, onchecking: null, ondownloading: null, onerror: null, …}
atob: ƒ atob()
blur: ƒ ()
btoa: ƒ btoa()
caches: CacheStorage {}
cancelAnimationFrame: ƒ cancelAnimationFrame()
cancelIdleCallback: ƒ cancelIdleCallback()
captureEvents: ƒ captureEvents()
chrome: {embeddedSearch: {…}, loadTimes: ƒ, csi: ƒ}
clearInterval: ƒ clearInterval()
clearTimeout: ƒ clearTimeout()
clientInformation: Navigator {vendorSub: "", productSub: "20030107", vendor: "Google Inc.", maxTouchPoints: 0, hardwareConcurrency: 4, …}
close: ƒ ()
closed: false
closure_lm_665802: _.Ye {src: Window, b: {…}, f: 4}
closure_uid_257079167: 1
colorArrayToHex: ƒ colorArrayToHex(color)
configData: {chromeColors: false, chromeColorsCustomColorPicker: false, enableShortcutsGrid: false, googleBaseUrl: "https://www.google.com/", hideShortcuts: false, …}
confirm: ƒ confirm()
createImageBitmap: ƒ createImageBitmap()
crypto: Crypto {subtle: SubtleCrypto}
customElements: CustomElementRegis
...
If you type window on the console, you get the object definition and you can see loads of different properties or methods attached to it. If you expand and see further, you can find alert(), setTimeout(), setInterval(), and various other methods that you have been using in your code till now.
Let's verify what we have just got to know. If these are methods or properties of the window object, we can access them using the window object.
alert() Method
window.alert('Hello world!');
Output:
Hello World
Voila! We get an alert saying hello world exactly how we would get it without using the window object.
setTimeout() Method
window.setTimeout(()=>{
console.log('This was printed after 5 second');
},5000);
Output:
This was printed after 5 second
Again we have used the window object to run our setTimeout() function.
Math Object
The Math object function is also built on to the window object.
window.Math.sqrt(64);
Output:
8
localStorage
The localStorage that is built on to the browser can also be accessed using the window object.
window.localStorage;
Output:
Storage {length: 0}
length: 0
__proto__: Storage
Some More Methods
Let's see some specific methods of the window object which will illustrate it's important use cases. Open a random tab in your browser and open the developer tools.
window.innerHeight;
window.innerWidth;
Output:
576
978
This property returns us the width and height of the current window frame. Now let's resize the window. Extend the console so that the window size shrinks or shrink the console so that the window size increases.
window.innerHeight;
window.innerWidth;
Output:
625
818
Thus on changing the size of the window we get different values of innerHeight and innerWidth which verifies that they are actually the window parameters that represent the total area that the web page is occupying.
While manipulating the DOM, we have used the document object to use the methods such as querySelector() or getElementById(), etc. The document object is also built on the window object.
Example:
Let's see a practical use case of this window object now.
Go to a folder of your choice and create an index.html file with the following starter template. We'll be learning how single-page websites bring you to the top of the web page on clicking a button.
Html Code:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="styles.css" />
<title>Window JS</title>
</head>
<body>
<h1>The window object</h1>
<div class="container">
<h3>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Aperiam doloremque sit impedit dolorem corporis, doloribus recusandae dolorum nemo consequuntur illum, officiis vel numquam non aliquid blanditiis quo atque aut
cupiditate!
</h3>
<br />
<hr />
<h3>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Suscipit enim eius distinctio similique, doloribus itaque ex repellat dolore! Dolor suscipit velit obcaecati in, magnam tenetur aperiam fugiat illum corrupti dicta.
</h3>
<br />
<hr />
<h3>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae corrupti dolore quam quasi. Mollitia suscipit maiores temporibus natus sapiente. Ex tempore praesentium sed debitis error sint. Dolores exercitationem quam eos.
</h3>
<h3>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Aperiam doloremque sit impedit dolorem corporis, doloribus recusandae dolorum nemo consequuntur illum, officiis vel numquam non aliquid blanditiis quo atque aut
cupiditate!
</h3>
<br />
<hr />
<h3>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Suscipit enim eius distinctio similique, doloribus itaque ex repellat dolore! Dolor suscipit velit obcaecati in, magnam tenetur aperiam fugiat illum corrupti dicta.
</h3>
<br />
<hr />
<h3>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae corrupti dolore quam quasi. Mollitia suscipit maiores temporibus natus sapiente. Ex tempore praesentium sed debitis error sint. Dolores exercitationem quam eos.
</h3>
<button id="btn">Get to the top</button>
</div>
<script></script>
</body>
</html>
In the styes.css add the following styles-
CSS Code (styes.css):
body {
background: whitesmoke;
}
h1 {
margin: 5px auto;
padding: 20px;
color: brown;
font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
text-align: center;
}
.container {
max-width: 400px;
padding-left: 400px;
text-align: center;
}
h3 {
text-align: center;
color: blueviolet;
background: rgba(64, 224, 208, 0.356);
font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}
button {
text-align: center;
padding: 10px;
background: steelblue;
color: white;
text-decoration: none;
cursor: pointer;
}
Output:
Now we have some dummy content on our page. To see all the content we need to scroll down. However, if we want to see the first content we will have to scroll all the way up. For a better user experience, we'll hook up functionality with the Get to the top button so that we reach the top of the web page in a single click and the user doesn't have to scroll up herself. Let's do this.
JavaScript Code:
<script>
var button = document.querySelector("#btn");
button.addEventListener("click", () => {
window.scrollTo(0, 0);
});
</script>
The scrollTo() method takes two parameters: x and y coordinates of the window space we want to scroll to. (0,0) takes us right to the top of the web page. Try it out by clicking the button and you automatically scroll to the top.
JavaScript Tutorial »