JS window object

The window object represents a window in the browser. It is automatically created by the browser when a web page is loaded. The window object is the top-level object in the Browser Object Model (BOM) and serves as the global object in client-side JavaScript.

The window object allows access to properties and methods that interact with the browser window, such as displaying alerts, opening new windows, and managing timeouts.

Properties of Window Object

Some important properties of the window object include:

window.document: Represents the HTML document loaded in the window.

window.history: Provides access to the browser's history.

window.screen: Provides information about the user's screen.

window.navigator: Contains information about the browser and the operating system.

window.location: Provides information about the current URL and allows URL redirection.

window.innerHeight: Returns the height of the window's content area.

window.innerWidth: Returns the width of the window's content area

Methods of Window Object

The important methods of the window object are as follows:

Method Description
alert() Displays an alert box containing a message with an OK button.
confirm() Displays a confirm dialog box containing a message with OK and Cancel buttons.
prompt() Displays a dialog box to get input from the user.
open() Opens a new window.
close() Closes the current window.
setTimeout() Performs an action after a specified time, such as calling a function or evaluating expressions.

Example:

<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Show Confirm</button>
<button onclick="showPrompt()">Show Prompt</button>
<button onclick="openNewWindow()">Open New Window</button>
<button onclick="closeWindow()">Close Window</button>
<button onclick="startTimeout()">Start Timeout</button>
<script>
    function showAlert() {
        window.alert("Hello, this is an alert box!");
    }<br>
    function showConfirm() {
        let result = window.confirm("Do you want to proceed?");
        if (result) {
            alert("You pressed OK!");
        } else {
            alert("You pressed Cancel!");
        }
    }<br>
    function showPrompt() {
        let userInput = window.prompt("Please enter your name:");
        if (userInput) {
            alert("Hello, " + userInput + "!");
        } else {
            alert("You didn't enter anything!");
        }
    }<br>
    function openNewWindow() {
        window.open("https://www.example.com", "_blank");
    }<br>
    function closeWindow() {
        window.close(); // This will only work if the window was opened by window.open()
    }<br>
    function startTimeout() {
        window.setTimeout(function() {
            alert("This message appears after 3 seconds!");
        }, 3000);
    }
</script>

Output: