Window object
The window object represents a browser window, and is automatically created by
the browser.
The window is an object provided by the browser, not by JavaScript itself.
JavaScript objects include types like String, Array, Date, etc.
Note:
If an HTML document contains a frame or iframe, the browser creates separate
window objects for each one.
Methods of window object
The key methods of the window object are as follows:
Example of alert() in javaScript
It displays an alert dialog box with a message and an OK button.
<input
type="button"
value="Click me"
onclick="showAlert()"
/>
<script>
function showAlert() {
alert('Hello, World!');
}
</script>
Example of confirm () in javaScript
It displays a confirmation dialog box with a message and OK and Cancel
buttons.
<input
type="button" value="Click me"
onclick="showConfirm()" />
<script>
function showConfirm() {
let result = confirm('Are you sure you want to delete this
file?');
if (result) {
alert('File deleted!');
} else {
alert('Deletion cancelled!');
}
}
</script>
Example of prompt () in javascript
It displays a prompt dialog box for input, featuring a message and a text
field.
<input
type="button"
value="Click me"
onclick="showPrompt()" />
<script>
function showPrompt() {
let name = prompt('Please enter your name:');
if (name !== null) {
alert('Hello, ' + name + '!');
} else {
alert('No name entered!');
}
}
</script>
Example of open () in javascript
It opens the content in a new window.
<input
type="button"
value="Click me"
onclick="openNewWindow()" />
<script>
function openNewWindow() {
window.open("(link unavailable)", "New Window",
"width=400,height=200");
}
</script>
Example of setTimeout() in javascript
It executes the task after the specified number of milliseconds.
<input
type="button"
value="Click me"
onclick="delayedAlert()" />
<script>
function delayedAlert() {
setTimeout(showAlert, 2000);
}
function showAlert() {
alert('Hello, World!');
}
</script>