JavaScript - window
The global object that represents the browser window or tab in which your webpage loads is called the window object in JavaScript. You can control the browser and interact with the webpage using its built-in properties, methods, and events, as well as its interface to the browser environment.
When a webpage loads, the browser immediately creates a window object, which includes all global variables, functions, and objects. Because of this, the window object is a necessary component of using online applications.
The JavaScript window object, its properties, functions, and events, as well as how to use it to handle browser-related activities, will all be covered in this blog post.
Example of Global Variables and Functions:
var myVar = 10;
function myFunction() {
console.log('This is a function');
}
console.log(window.myVar); // Output: 10
window.myFunction(); // Output: This is a function
In this example, myVar and myFunction are part of the global scope and can be accessed via the window object.
2. Window Properties
The window object contains several properties that provide information about the browser and the document being displayed.
Common Window Properties:
window.innerWidth and window.innerHeight: Returns the width and height of the browser's content area (viewport).
window.outerWidth and window.outerHeight: Returns the width and height of the browser window including toolbars, scrollbars, etc.
window.location: Provides information about the current URL and allows you to manipulate it.
window.document: Represents the DOM (Document Object Model) of the page loaded in the window.
window.history: Provides access to the browser's session history (the pages the user has visited).
window.navigator: Contains information about the browser and the operating system.
Example of Using Window Properties:
console.log('Inner Width:', window.innerWidth); // Output: Current viewport width
console.log('Outer Height:', window.outerHeight); // Output: Full window height
console.log('Current URL:', window.location.href); // Output: Current URL
3. Window Methods
The window object provides several built-in methods that allow you to perform various actions, such as opening new windows, displaying alerts, and navigating between pages.
Common Window Methods:
window.alert(): Displays an alert box with a message.
window.confirm(): Displays a confirmation dialog with OK and Cancel buttons.
window.prompt(): Displays a dialog box that prompts the user for input.
window.open(): Opens a new browser window or tab.
window.close(): Closes the current browser window or tab.
window.setTimeout(): Executes a function after a specified delay (in milliseconds).
window.setInterval(): Repeatedly executes a function at specified time intervals.
Example of Using Window Methods:
window.alert('Hello, World!'); // Displays an alert box
const userConfirmation = window.confirm('Are you sure?'); // Displays a confirmation dialog
console.log(userConfirmation); // Output: true or false based on the user's choice
const userName = window.prompt('What is your name?'); // Prompts user input
console.log(userName); // Output: User's input
Example of setTimeout and setInterval:
// Delayed execution after 2 seconds
window.setTimeout(() => {
console.log('This message is delayed by 2 seconds.');
}, 2000);
// Repeated execution every 3 seconds
let counter = 0;
const intervalId = window.setInterval(() => {
console.log('Interval count:', ++counter);
if (counter === 5) {
window.clearInterval(intervalId); // Stops the interval after 5 executions
}
}, 3000);
4. Window Events
The window object can also respond to various events triggered by the user or the browser itself. Common events include resizing the window, loading the page, scrolling, and closing the window.
Common Window Events:
window.onload: Fired when the entire page (including all dependent resources) has fully loaded.
window.onresize: Fired when the browser window is resized.
window.onscroll: Fired when the user scrolls the webpage.
window.onbeforeunload: Fired when the user is about to leave the page.
Example of Handling Window Events:
// Execute code when the page is fully loaded
window.onload = function() {
console.log('Page has fully loaded.');
};
// Execute code when the window is resized
window.onresize = function() {
console.log('Window resized to:', window.innerWidth, 'x', window.innerHeight);
};
// Execute code when the user scrolls the page
window.onscroll = function() {
console.log('Page scrolled. Scroll position:', window.scrollY);
};
// Warn the user before they leave the page
window.onbeforeunload = function() {
return 'Are you sure you want to leave this page?';
};
In this example, various window events are captured, and corresponding actions are performed.
5. Working with Window Location
The window.location property provides information about the current URL of the webpage and allows you to navigate to different URLs.
Window Location Properties:
window.location.href: The full URL of the current page.
window.location.hostname: The domain name of the web host.
window.location.pathname: The path of the current page.
window.location.protocol: The protocol used (http: or https:).
window.location.assign(): Loads a new document in the current window.
Example of Using Window Location:
console.log('Current URL:', window.location.href); // Output: Full URL
console.log('Hostname:', window.location.hostname); // Output: Domain name
console.log('Pathname:', window.location.pathname); // Output: Path part of the URL
// Navigate to a new page
window.location.assign('https://www.example.com');
6. Controlling Browser History
The window.history object provides methods to manipulate the browser history, allowing you to move forward, backward, or go to a specific page in the user's browsing history.
Common History Methods:
window.history.back(): Navigate to the previous page in the history.
window.history.forward(): Navigate to the next page in the history.
window.history.go(): Navigate to a specific point in the history list. A negative value goes back in history, while a positive value moves forward.
Example of Using History Methods:
// Go back one page
window.history.back();
// Go forward one page
window.history.forward();
// Go back two pages in the history
window.history.go(-2);
7. Managing Timers with setTimeout and setInterval
JavaScript provides two essential methods, setTimeout and setInterval, to schedule code execution after a specified delay or at regular intervals.
Example of Using setTimeout:
setTimeout(() => {
console.log('This message is shown after 3 seconds');
}, 3000);
Example of Using setInterval:
let count = 0;
const intervalId = setInterval(() => {
count += 1;
console.log('Count:', count);
if (count === 5) {
clearInterval(intervalId); // Stop the interval after 5 iterations
}
}, 1000);
8. Conclusion
A key component of dealing with the browser environment is the JavaScript window object. You can adjust the URL, handle events, control the browser window, and communicate with users by sending them notifications, prompts, and confirmations thanks to its extensive collection of attributes and methods. Building reliable, interactive web apps requires a basic understanding of the window object.
You can make more dynamic, user-friendly online experiences by becoming proficient with the window object and its features.