Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
When you are working with client-side JavaScript, which runs on the browser, you could use the window object, and it’s essential to learn how the window object works because that is how Javascript interacts with the browser. In order to communicate with the browser, javaScript uses something called the Browser Object Model(BOM), which deals with all the components from the browser. Think about the history, the location, the navigation, the height and the width of the screen, the document object(HTML DOM), the alert() function you use or even the console.log() that we often use and many many more, where do you think these come from? Well, all these things are part of the window object.
In this article, we will learn about the Window object in JavaScript, a core part of the browser's Document Object Model (DOM). The Window object represents the browser window or tab, providing access to various properties and methods that control the browser environment, including functions for displaying alerts, retrieving screen dimensions, handling navigation, and much more.
For example, let’s use the alert() function to get a pop-up window showing us ‘Hello world!’.
window.alert("Hello world!");
You can omit this window keyword if you want to, as the window is the global object and the parent of all the things present globally in javaScript. So, all global JavaScript objects, functions, and variables automatically become members of the window object. By default, it is understood that alert() is the member of the window object.
This is the same as above,
alert("Hello world!");
Similarly, console.log() is also the member of the window object.
window.console.log("Hello world!");
Same as,
console.log("Hello world!");
What is window object in Javascript?
One important note is that the window object is only available to the javaScript working in the browser. Any other JavaScript runtime environment such as Node.js doesn’t have access to this window object.
Now, let’s explore this window object by logging it to the console,
console.log(window);
You’ll see this become a gigantic object containing tons of properties and methods,
When we declare variables, objects, and functions globally in javaScript, it also becomes a member of this object.
For example, let’s declare a variable and see if it becomes a member of this window object or not.
var iAmInsideWindow = "Hey! I am inside the window";
Well, see, it is inside of this object, i.e., it becomes the member of the window object.
So, often it is not recommended to declare variables with var in the global scope as it clutters the window object. Always use let to declare variables as it doesn’t become a member of the window object, and hence the window object remains neat and clean.
By looking at this object, we’ll see all the properties such as alert, clearInterval, setInterval, etc., are present inside it. Each tab in a browser contains its own window object.
We as wise developers, just have to exploit these properties for our specific use-cases. We will examine some of its properties to embrace the browser’s functionality.
Properties of Javascript Object
Given below a table of the commonly used window object properties:
Method
Description
closed
returns a boolean value that specifies whether a window has been closed or not
document
specifies a document object in the window. It forms the basis of DOM(Document Object Model).
history
specifies a history object for the window. The history object contains the URLs visited by the user (within a browser window).
defaultStatus
specifies the default message that has to appear in the status bar of Window.
innerHeight
specifies the height of the viewport of the page i.e, the window's content area.
innerWidth
specifies the width of the viewport of the page i.e, the window's content area.
location
specifies the location object for the window
name
specifies the name for the window
status
specifies the message that is displayed in the status bar of the window when an activity is performed on the Window.
screenLeft
specifies the x coordinate of the window relative to a user's monitor screen
screenTop
Specifies the y coordinate of the window relative to a user's monitor screen
screenX
specifies the x coordinate for window relative to a user's monitor scree
screenY
Specifies the y coordinate for window relative to a user's monitor screen.
Assuming the viewport size is 1200px wide and 800px high:
Viewport width: 1200
Viewport height: 800
Example 2: window.location
The window.location property provides information about the current URL and allows navigation to other pages.
// Display the current URL
console.log("Current URL:", window.location.href);
// Redirect to another page
// window.location.href = "https://www.example.com";
You can also try this code with Online Javascript Compiler
If the current page URL is https://www.currentpage.com
Current URL: https://www.currentpage.com
JavaScript window object methods
The JavaScript window object offers methods to interact with the browser, like displaying alerts, opening or closing new tabs, and confirming user actions. Here’s a look at some common methods and their syntax:
Syntax of Window Object Methods in JavaScript
The syntax for JavaScript window object methods generally follows the format:
window.methodName(arguments);,
where, window can be omitted, as it’s the global object by default.
Given below a table of the commonly used window object methods:
Method
Description
window.close()
Closes the current browser window, but it can only close windows opened by window.open().
window.open()
Opens a new browser window or tab with a specified URL and can accept parameters for target and window features.
alert()
Displays an alert box that pops up with a message and an OK button.
blur()
Removes the focus from the current window.
window.postMessage()
Sends messages between different windows or iframes, allowing secure communication even if they are from different origins.
clearInterval()
Clears the timer set by the setInterval() method.
close()
Closes the current window.
confirm()
Displays a dialogue box with a message and two buttons: OK and Cancel.
focus()
Sets the focus on the current window.
open()
Opens a new browser window.
moveTo()
Moves a window to a specified position.
moveBy()
Moves a window relative to its current position.
prompt()
Prompts for input.
print()
Sends a print command to print the content of the current window.
setTimeout()
Evaluates an expression after a specified number of milliseconds.
setInterval()
Evaluates an expression at specified time intervals (in milliseconds).
resizeBy()
Specifies the amount by which the window will be resized.
resizeTo()
Used for dynamically resizing the window.
scroll()
Scrolls the window to a particular place in the document.
scrollBy()
Scrolls the window by the given value.
stop()
Stops the window loading.
Example of Window Object Method in JS
Example 1 - Getting the size of the browser’s window
Let’s get the size of the browser’s window using the window object. We will use the innerWidth and innerHeight properties of this object to get the viewport size of the page inside the browser window. To get the size of the entire browser window, we will use the outerWidth and outerHeight properties.
In javaScript, we have added an event listener ‘resize’ that responds to the event when we resize the browser window and then accordingly the innerHeight, innerWidth, outerWidth and outerHeight properties shows the width and height. The addEventListener() method is also part of the window object. Every time you resize your browser window, you will get different heights and widths.
We then grabbed the ‘p’ element using its id and called the update() function. Inside update() function, we have embedded some HTML inside the p element using the innerHTML property and then we have precisely used the size properties of the window to get our desired widths and heights.
Example 2 - Opening a new window
We can open a new window or a new tab in a browser using the window object. We’ll be using the window.open() method for this.
window.open(url, windowName, [windowFeatures]);
This function takes three arguments. The first one is the URL of the website you want to open on the new window, then the second option is the name of the window as per your choice, and the third argument is features or the options that we can set to open the window accordingly.
For example, see, we’ve specified various options like scrollbars=false and many other options. But one thing to note is that not all the options specified by you are applied to the new window as it depends on browser to browser. See the output below, scrollbars are also there even if we set it to false.
let newWindow = window.open("http://youtube.com","myWindow", "menubar=true,location=true,resizable=false,scrollbars=false,width=400,height=300,top=200,left=200");
Output
The new window popped up.
Example 3 - Closing the window
Let’s close the above-opened window. We will use the close() method to the newWindow variable. Like this, newWindow.close()
For example, we will create a button and add an onclick attribute to listen to the click event. We’ve specified the newWindow.close() as its value which closes the opened window.
<html>
<head>
<title>JavaScript Window</title>
</head>
<body>
<h1>Click this button to close the window</h1>
<button onclick="newWindow.close()">Close window</button>
</body>
<script>
let newWindow = window.open(
"http://youtube.com", "myWindow", "menubar=true,location=true,resizable=false,scrollbars=false,width=400,height=300,top=200,left=200"
);
</script>
</html>
You can also try this code with Online Javascript Compiler
By clicking on the button, we can close the window,
Example 4 - Moving a window
We can use the moveBy() method to move the opened window. moveBy() takes dimensions i.e, how much to move in which direction. Like we moved 50px left and 0px down. Like this,
newWindow.moveBy(50, 0)
<html>
<head>
<title>JavaScript Window</title>
</head>
<body>
<h1>Click this button to move a window</h1>
<button onclick="move()">Move window</button>
</body>
<script>
let newWindow = window.open(
"http://youtube.com", "myWindow", "menubar=true,location=true,resizable=false,scrollbars=false,width=400,height=300,top=200,left=200"
);
function move() {
newWindow.moveBy(50, 0);
newWindow.focus()
}
</script>
</html>
You can also try this code with Online Javascript Compiler
We’ve used the focus() method to just pop the window to the top of the screen. So if the window is behind another window, focus() will make it pop to the top of the screen.
Example 5 - Loading different websites on a newly opened window
Remember we’ve passed the name of the window of our choice as a second argument insidethe window.open() method. So, what’s the purpose of giving a name to the window? Well, we can do amazing stuff like opening a link on that new window by utilizing its name.
We will specify the name of the window to the target attribute of the anchor tag of the HTML. Like this,
<a href="http://facebook.com" target="myWindow">Go to Facebook</a>
This will open up facebook.com on our new window named ‘myWindow.’
<html>
<head>
<title>JavaScript Window</title>
</head>
<body>
<h1>Click this button to move a window</h1>
<a href="http://facebook.com" target="myWindow">Go to Facebook</a>
</body>
<script>
let newWindow = window.open(
"http://youtube.com", "myWindow",
"menubar=true,location=true,resizable=false,scrollbars=false,width=400,height=300,top=200,left=200"
);
</script>
</html>
You can also try this code with Online Javascript Compiler
Now after clicking the link, it will open up facebook.com on the new window.
Frequently asked questions
What is a JavaScript window object?
This is a top-level parent object which contains all the properties and methods. By utilizing these properties and methods we can exploit the capabilities of the browser.
Is the window object always available in JavaScript?
Yes, the window object is always available in JavaScript when running in a browser. It represents the browser window and serves as the global object for all JavaScript code, allowing access to various browser functionalities.
How does the window object relate to the global scope in JavaScript?
In JavaScript, the window object is the global scope for code running in the browser. This means that global variables and functions are properties of the window object, allowing easy access without explicitly referencing it.
What’s the difference between window and document in JavaScript?
The window object represents the entire browser window, while the document object refers specifically to the HTML document loaded in that window. The window object contains methods for managing the browser, whereas the document object is used to manipulate the DOM.
Conclusion
The JavaScript window object is vital for web development, providing access to essential browser features. By understanding its properties and methods, developers can effectively manage browser windows, handle events, and manipulate the DOM, leading to more interactive and dynamic web applications.
You can also learn JavaScript from scratch with our Code360 Guided Path for JavaScript. And if you think you already have good knowledge of JavaScript then you can check our article on JavaScript interview questions and JavaScript Cheat Sheet which will help you in ace interviews for web development.