JavaScript Window
Understanding the browser window object
🪟 What is the Window Object?
The Window object represents the browser window and is the global object in JavaScript. All global variables and functions become properties of the window object.
// These are all the same thing
console.log("Hello World");
window.console.log("Hello World");
// Global variables become window properties
var myVar = "Hello";
console.log(window.myVar); // "Hello"
Output:
Hello World
Hello World
Hello
Common Window Properties
Window Size
Get browser window dimensions
console.log(window.innerWidth);
console.log(window.innerHeight);
Location
Current page URL information
console.log(window.location.href);
console.log(window.location.hostname);
Document
Access the HTML document
console.log(window.document.title);
window.document.body.style.background = "lightblue";
History
Browser navigation history
window.history.back();
window.history.forward();
🔹 Window Methods
The window object provides many useful methods:
// Open a new window
window.open("https://example.com", "_blank");
// Close current window
window.close();
// Print the page
window.print();
// Scroll to position
window.scrollTo(0, 100);
// Get window size
var width = window.innerWidth;
var height = window.innerHeight;
console.log("Window size: " + width + "x" + height);
Try this:
🔹 Window Events
Listen for window events to respond to user actions:
// When page loads
window.onload = function() {
console.log("Page loaded!");
};
// When window resizes
window.onresize = function() {
console.log("Window resized to: " + window.innerWidth + "x" + window.innerHeight);
};
// When page is about to unload
window.onbeforeunload = function() {
return "Are you sure you want to leave?";
};
// Scroll event
window.onscroll = function() {
console.log("Page scrolled!");
};
Try resizing your browser window to see the resize event!
🔹 Practical Examples
Here are some practical uses of the window object:
🔸 Responsive Design Check
function checkScreenSize() {
if (window.innerWidth < 768) {
console.log("Mobile device");
document.body.style.fontSize = "14px";
} else {
console.log("Desktop device");
document.body.style.fontSize = "16px";
}
}
// Check on load and resize
window.onload = checkScreenSize;
window.onresize = checkScreenSize;
🔸 Smooth Scroll to Top
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
// Add a button to scroll to top
document.body.innerHTML += '';