Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
A closer look at the window object
3.
Some common window object properties
4.
 
5.
Some common window object methods
6.
Getting the size of the browser’s window
7.
Opening a new window
8.
Closing the window
9.
Moving a window
10.
Loading different websites on a newly opened window
11.
Frequently asked questions
12.
Key takeaways
Last Updated: Mar 27, 2024

JavaScript Window

Author Aditya kumar
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

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.

 

 

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!");

 

A closer look at the window object

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 vast, becomes 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 alertclearIntervalsetInterval, 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. 

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Some common window object properties

Given below a table of the commonly used window object properties:

Property

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 screen
screenY Specifies the y coordinate for window relative to a user's monitor screen

 

 

You can implement code on an online JS editor.

Some common window object methods

Given below a table of the commonly used window object methods:

Method

Description

alert() displays an alert box that pops up with a message and an OK button.
blur() removes the focus from the current window.
clearInterval() clears the timer, which is set by using 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() this method 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 document
scrollBy() scrolls the window by the given value
stop() stops window loading

 

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.

 

Like this,

 

 

<html>

  <head>

    <title>JavaScript Window</title>

  </head>

  <body>

    <h1>Know your window's size</h1>

    <p id="elem"></p>

  </body>

  <script>

    window.addEventListener("resize"update);

 

    let elem = document.getElementById("elem");

    update();

 

    function update() {

      elem.innerHTML =

        "Browser inner width: " +

        window.innerWidth +

        "px and inner height: " +

        window.innerHeight +

        "px.<br> Browser outer width: " +

        window.outerWidth +

        "px and outer height: " +

        window.outerHeight +

        "px.";

    }

  </script>

</html>

 

In javaScript, we have added an event listener ‘resize’ that responds to the event when we resize the browser window and then accordingly the innerHeightinnerWidthouterWidth 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 element using the innerHTML property and then we have precisely used the size properties of the window to get our desired widths and heights.

 

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(urlwindowName, [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");

 

The new window popped up,

 

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>

 

 

By clicking on the button,, we can close the window,

 

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(500)

 

<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(500);

      newWindow.focus()

    }

  </script>

</html>

 

 

 

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.

 

Loading different websites on a newly opened window

Remember we’ve passed the name of the window of our choice as a second argument inside the 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>

 

 

The window opens up with youtube.com,

 

 

Now after clicking the link, it will open up facebook.com on the new window,

 

 

Frequently asked questions

  1. 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.
     
  2. Which properties are used for getting the size of the browser window?
    innerWidth and innerHeight for the viewport and outerWidth and outerWidth for the entire browser window.
     
  3. Does the window object is same in all the browsers?
    No, it varies from browser to browser. Some of the properties and methods may be different in some browsers, and some may be missing.

Key takeaways

So finally, we’ve reached the end of the article. Congratulations! If you made it this far. This will surely help you establish a firm grip on this topic. To summarize this, we started by introducing the window object. We had a closer look at this gigantic object and explored some of its most common properties and methods to take advantage of the browser’s functionality.

You can also learn JavaScript from scratch with our Coding Ninjas 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.

 

Previous article
JavaScript BOM
Next article
JavaScript Screen, Location, and History
Live masterclass