Understanding the JavaScript Window Object
The Window object is the global object in client-side JavaScript, representing the browser window or tab. It serves as the entry point for the Document Object Model (DOM) and provides methods, properties, and events to interact with the browser window.
Core Concepts
1. Window Properties
// Get window dimensions
console.log("Window width:", window.innerWidth);
console.log("Window height:", window.innerHeight);
// Get screen information
console.log("Screen width:", window.screen.width);
console.log("Screen height:", window.screen.height);
// Get browser location
console.log("Current URL:", window.location.href);
console.log("Hostname:", window.location.hostname);
// Get browser information
console.log("User Agent:", window.navigator.userAgent);
2. Window Methods
Opening and Closing Windows
// Open a new window
const newWindow = window.open("https://www.example.com", "exampleWindow", "width=600,height=400");
// Close the current window (may be blocked by browsers)
// window.close();
// Example with basic HTML button
<button onclick="openExampleWindow()">Open Example Window</button>
<button onclick="closeExampleWindow()">Close Example Window</button>
<script>
let exampleWindow;
function openExampleWindow() {
exampleWindow = window.open("", "example", "width=300,height=200");
exampleWindow.document.write("<h2>New Window</h2><p>This is a new window!</p>");
}
function closeExampleWindow() {
if (exampleWindow) {
exampleWindow.close();
}
}
</script>
Alert, Confirm, and Prompt
// Alert dialog
window.alert("This is an alert message!");
// Confirm dialog (returns boolean)
const isConfirmed = window.confirm("Are you sure you want to proceed?");
console.log("User confirmed:", isConfirmed);
// Prompt dialog (returns string or null)
const userName = window.prompt("Please enter your name:", "John Doe");
console.log("User entered:", userName);
Timing Methods
// setTimeout - executes code once after delay
const timeoutId = window.setTimeout(() => {
console.log("This message appears after 2 seconds");
}, 2000);
// setInterval - executes code repeatedly
let counter = 0;
const intervalId = window.setInterval(() => {
counter++;
console.log(`Counter: ${counter}`);
if (counter >= 5) {
window.clearInterval(intervalId); // Stop the interval
}
}, 1000);
// Clear timeout example
<button onclick="startTimer()">Start Timer</button>
<button onclick="cancelTimer()">Cancel Timer</button>
<script>
let timerId;
function startTimer() {
timerId = setTimeout(() => {
alert("Time's up!");
}, 5000);
console.log("Timer started");
}
function cancelTimer() {
if (timerId) {
clearTimeout(timerId);
console.log("Timer cancelled");
}
}
</script>
3. Window Events
// Load event - fires when page fully loads
window.addEventListener('load', function() {
console.log("Page fully loaded");
});
// Resize event - fires when window is resized
window.addEventListener('resize', function() {
console.log(`Window resized to: ${window.innerWidth}x${window.innerHeight}`);
});
// Scroll event
window.addEventListener('scroll', function() {
console.log(`Scrolled to: ${window.scrollY}px from top`);
});
// Beforeunload event - fires when user tries to leave page
window.addEventListener('beforeunload', function(e) {
const message = "Are you sure you want to leave?";
e.returnValue = message; // Standard method
return message; // For older browsers
});
4. Window Location Object
// Get current URL information
console.log("Full URL:", window.location.href);
console.log("Protocol:", window.location.protocol);
console.log("Host:", window.location.host);
console.log("Path:", window.location.pathname);
console.log("Query parameters:", window.location.search);
// Navigation methods
window.location.assign("https://www.example.com"); // Navigate to new page
window.location.reload(); // Reload current page
// window.location.replace("https://www.example.com"); // Replace current page in history
// Example: Redirect after delay
setTimeout(() => {
window.location.href = "https://www.example.com";
}, 3000);
5. Window History Object
// Navigation history
console.log("History length:", window.history.length);
// Navigation methods
window.history.back(); // Go back one page
window.history.forward(); // Go forward one page
window.history.go(-2); // Go back two pages
// Example with basic HTML buttons
<button onclick="goBack()">Go Back</button>
<button onclick="goForward()">Go Forward</button>
<script>
function goBack() {
window.history.back();
}
function goForward() {
window.history.forward();
}
</script>
6. Window LocalStorage and SessionStorage
// LocalStorage - persists across browser sessions
window.localStorage.setItem("username", "john_doe");
const username = window.localStorage.getItem("username");
console.log("Username from localStorage:", username);
// SessionStorage - persists only for current session
window.sessionStorage.setItem("theme", "dark");
const theme = window.sessionStorage.getItem("theme");
console.log("Theme from sessionStorage:", theme);
// Remove items
window.localStorage.removeItem("username");
window.sessionStorage.clear(); // Remove all sessionStorage items
7. Window Object as Global Scope
// Variables declared with var become properties of window
var globalVar = "I'm global";
console.log(window.globalVar); // "I'm global"
// Functions become methods of window
function globalFunction() {
return "I'm a global function";
}
console.log(window.globalFunction()); // "I'm a global function"
// let and const declarations don't become window properties
let localLet = "I'm local";
const localConst = "I'm also local";
console.log(window.localLet); // undefined
console.log(window.localConst); // undefined
Practical Examples
Example 1: Responsive Layout
// Check window size and adjust layout
function checkLayout() {
if (window.innerWidth < 768) {
console.log("Mobile layout");
document.body.style.fontSize = "14px";
} else if (window.innerWidth < 1024) {
console.log("Tablet layout");
document.body.style.fontSize = "16px";
} else {
console.log("Desktop layout");
document.body.style.fontSize = "18px";
}
}
// Run on load and resize
window.addEventListener('load', checkLayout);
window.addEventListener('resize', checkLayout);
Example 2: Page Load Progress
// Simulate page loading progress
window.addEventListener('load', function() {
let progress = 0;
const loadingInterval = setInterval(() => {
progress += 10;
console.log(`Loading: ${progress}%`);
if (progress >= 100) {
clearInterval(loadingInterval);
console.log("Page fully loaded!");
}
}, 200);
});
The Window object is fundamental to browser JavaScript, providing access to browser features, navigation, storage, and much more. Understanding its properties and methods is essential for web development.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.