Advance JavaScript (DOM, BOM, Web API) / Browser Object Model (BOM)

Window

πŸ“Œ What is window?

The window object represents the browser window or tab.

It is the global object in JavaScript (in browsers).

πŸ‘‰ Everything runs inside window:

  • Global variables

  • Global functions

  • DOM (document)

  • BOM (location, history, etc.)


🌍 Global Scope & window

Example

var name = "Bhaskar";

function greet() {
  console.log("Hello");
}

Explanation

  • var variables and normal functions declared globally become properties of window.

console.log(window.name);
window.greet();
Bhaskar
Hello

⚠️ let and const do not attach to window.


🧩 Common window Properties

Property

Explanation

window.document

Accesses the HTML page (DOM)

window.location

Gives URL details

window.history

Controls back/forward

window.navigator

Browser information

window.screen

Screen size info


πŸ”” Window Methods

1️⃣ alert()

alert("Welcome!");

Explanation:

Shows a popup message to the user.

2️⃣ confirm()

const result = confirm("Are you sure?");
console.log(result);

Explanation:

  • User clicks OK β†’ true

  • User clicks Cancel β†’ false

3️⃣ prompt()

const name = prompt("Enter your name:");
console.log(name);

Explanation:

Takes input from the user.


⏱️ Window Timers

setTimeout()

setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);

Explanation:

Runs code once after delay.

Executed after 2 seconds

setInterval()

setInterval(() => {
  console.log("Running...");
}, 1000);

Explanation:

Runs code repeatedly every 1 second.

Running...
Running...
Running...

πŸ“ Window Size

console.log(window.innerWidth);
console.log(window.innerHeight);

Explanation:

Returns the viewport width & height.

1366
768

🌐 Open & Close Window

const newTab = window.open("<https://example.com>");
newTab.close();

Explanation:

  • open() opens a new tab/window

  • close() closes it (only if opened by JS)


🎯 Window Events

Page Load

window.onload = () => {
  console.log("Page fully loaded");
};

Explanation:

Runs when the entire page (HTML, CSS, images) is loaded.

Page fully loaded

Window Resize

window.onresize = () => {
  console.log("Window resized");
};

Explanation:

Triggers whenever browser size changes.

Window resized


πŸ†š Window vs Document

Window

Document

Browser/tab

Web page

BOM object

DOM object

Controls browser

Controls HTML


⭐ Important Notes

  • window is the root object

  • You can omit window.

    alert("Hi"); // same as window.alert()
  • Global var β†’ attached to window


βœ… Summary

  • window = browser control center

  • Parent of DOM & BOM

  • Used for alerts, timers, navigation, and global access