Popup & Alert
JavaScript provides several built-in methods to display popup dialogs in the browser. These methods are part of the Browser Object Model (BOM) and are accessible via the window
object. They allow developers to interact with users, show messages, collect input, or ask for confirmations.
alert()
– Simple Message Popup
The alert()
method displays a modal dialog with a specified message and an OK button. It is commonly used to show notifications or warnings.
Syntax:
alert(message);
Example:
alert("Hello! Welcome to our website.");
confirm()
– Confirmation Dialog
The confirm()
method displays a modal dialog with a message, an OK button, and a Cancel button. It is used when you want the user to confirm an action.
Syntax:
const result = confirm(message);
result
is a boolean: true
if the user clicks OK, false
if Cancel.
Example:
const deleteConfirm = confirm("Are you sure you want to delete this item?");
if(deleteConfirm) {
console.log("Item deleted");
} else {
console.log("Action canceled");
}
prompt()
– Input Dialog
The prompt()
method displays a modal dialog that asks the user to input text. It shows a message, an optional default value, and an input field.
Syntax:
const userInput = prompt(message, defaultValue);
Example:
const name = prompt("Please enter your name:", "Guest");
if(name) {
alert(`Hello, ${name}!`);
} else {
alert("No name entered");
}
Practical Example – Combined Popup Usage
// Alert
alert("Welcome to our site!");
// Confirm
const proceed = confirm("Do you want to continue?");
if(proceed) {
// Prompt for input
const age = prompt("Enter your age:", "18");
if(age) {
alert(`You entered: ${age}`);
} else {
alert("No age entered");
}
} else {
alert("Action canceled");
}