JavaScript Window

The window object in JavaScript represents the browser's window or tab. It is the global object in the browser environment, providing access to the browser's features and DOM elements.

Key Topics

Window Methods

The window object provides methods to interact with the browser, such as alert, prompt, and confirm.

window.alert("This is an alert box!");
let userName = window.prompt("What is your name?");
let isConfirmed = window.confirm("Do you agree?");
console.log(userName, isConfirmed);

Output

(An alert box, a prompt dialog, and a confirmation box appear.)

Explanation: The alert, prompt, and confirm methods provide user interaction capabilities. The input and confirmation values are logged to the console.

Window Properties

Properties of the window object provide information about the browser environment, such as dimensions and the current URL.

console.log("Window Width:", window.innerWidth);
console.log("Window Height:", window.innerHeight);
console.log("Current URL:", window.location.href);

Output

> Window Width: [Current Width]

> Window Height: [Current Height]

> Current URL: [Current URL]

Explanation: The innerWidth and innerHeight properties return the viewport size, while window.location.href retrieves the current URL.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating how to use window methods and properties.

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript Window Example</title>
    </head>
    <body>
        <button onclick="showInfo()">Show Info</button>
        <script>
            function showInfo() {
                alert("Screen Width: " + window.innerWidth);
                alert("Screen Height: " + window.innerHeight);
                let userName = prompt("Enter your name:");
                console.log("Name entered:", userName);
            }
        </script>
    </body>
</html>

Key Takeaways

  • Global Object: The window object is the global scope in the browser.
  • Methods: Use alert, prompt, and confirm for user interactions.
  • Properties: Access information like dimensions and the current URL using properties.
  • Dynamic Interaction: Utilize the window object for user interaction and browser control.