In JavaScript, the window object model represents the browser window that contains the current web page. The window object is a global object, which means that its properties and methods can be accessed from anywhere in the code.
Here, are some common properties and methods of the window object.
These properties return the height and width of the browser window, in pixels.
var w = window.innerWidth;
var h = window.innerHeight;
alert("Width: " + w + ", " + "Height: " + h);
This method opens a new browser window or tab, and navigates it to the specified URL with defined width and height.
window.open("https://www.tutorialsTrend.com", "_blank", "width=800,height=600");
This method closes the current browser window or tab.
window.close();
This method displays a dialog box with a message and an OK button.
window.alert("Hello, world!");
This method displays a dialog box with a message, an input field, and OK and Cancel buttons.
const result = window.prompt("What is your name?");
if (result) {
window.alert(`Hello, ${result}!`);
}
This method displays a dialog box with a message, OK and Cancel buttons, and returns true if the user clicks OK and false if the user clicks Cancel.
const result = window.confirm("Are you sure you want to delete this item?");
if (result) {
window.alert("Item deleted.");
}
Here's an example of how to use the window object in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Window Example</title>
<style>
button {
background: bisque;
}
</style>
</head>
<body>
<h2>TutorialsTrend - BOM Examples</h2>
<button onclick="windowSize()">Show Window Size</button>
<button onclick="openWindow()">Open Window</button>
<button onclick="closeWindow()">Close Window</button>
<button onclick="showAlert()">Show Alert</button>
<button onclick="showPrompt()">Show Prompt</button>
<button onclick="showConfirm()">Show Confirm</button>
<script>
function windowSize() {
var w = window.innerWidth;
var h = window.innerHeight;
alert("Width: " + w + ", " + "Height: " + h);
}
function openWindow() {
window.open("https://www.tutorialsTrend.com", "_blank", "width=800,height=600");
}
function closeWindow() {
window.close();
}
function showAlert() {
window.alert("Hello, world!");
}
function showPrompt() {
const result = window.prompt("What's your name?");
if (result) {
window.alert(`Hello, ${result}!`);
}
}
function showConfirm() {
const result = window.confirm("Are you sure you want to delete this item?");
if (result) {
window.alert("Item deleted.");
}
}
</script>
</body>
</html>
Output
Now click on the Show window size. The below alert box will be show the width and height.
Now click on the open window button the open another window with given URL
You can also test other buttons effect one by one.