JavaScript Pop-up Boxes
In JavaScript, you can create popup boxes to interact with users using the alert()
, confirm()
, and prompt()
functions. These functions provide simple ways to display messages, ask for user confirmation, and prompt the user for input.
1. Alert Box (alert()
):
The alert()
function displays a message to the user in a dialog box with an “OK” button.
alert("Hello, world!");
2. Confirm Box (confirm()
):
The confirm()
function displays a message to the user in a dialog box with “OK” and “Cancel” buttons. It returns true
if the user clicks “OK” and false
if the user clicks “Cancel”.
let result = confirm("Are you sure you want to proceed?");
if (result) {
console.log("User clicked OK");
} else {
console.log("User clicked Cancel");
}
3. Prompt Box (prompt()
):
The prompt()
function displays a dialog box that prompts the user for input. It returns the text entered by the user, or null
if the user clicks “Cancel”.
let name = prompt("What is your name?");
if (name !== null) {
console.log("Hello, " + name + "!");
} else {
console.log("User clicked Cancel");
}
These popup boxes can be useful for displaying messages, confirming user actions, and gathering input from the user in a simple and straightforward manner. However, they can also be intrusive and should be used judiciously to provide a better user experience.