In JavaScript, there are three types of popup boxes:
- Alert Box.
- Confirm Box.
- Prompt Box.
Here is the syntax for using each of them:
// Alert window.alert("something"); // Confirm window.confirm("something"); // Prompt window.prompt("something", "default text");
This is a complete guide to popups in JavaScript. You will learn how and why to use the three different popup types in JavaScript. The guide shows you simple and illustrative examples.
JavaScript Popup Modals
Here is a table that summarizes the use of the three JavaScript popups:
Name | Use Case | Example |
---|---|---|
1. Alert Box | Warn users | window.alert(“Too many windows open!“); |
2. Confirmation Box | Ask for user confirmation before accessing the page | window.confirm(“Do you want to proceed?“); |
3. Prompt Box | Ask for the user input | window.prompt(“Give your name“, “Unnamed“); |
Now, let’s take a closer look at how each popup modal works in JavaScript.
1. Alert Box
In JavaScript, you can message or warn a user with an alert box. When a user sees an alert box, they have to click “OK” to proceed.
You can create an alert box with the built-in alert() method. This method takes one argument which is the alert message to be displayed.
Here is an example of how to create an alert box in JavaScript:
alert("Enable JavaScript to Continue on the Site!");
Output:
2. Confirmation Box
The confirmation popup box is used to display a dialog with a message and two buttons, “OK” and “Cancel”.
To create a confirmation box, use the built-in confirm() method. This method takes one argument which specifies the confirmation message to be displayed.
The confirmation box (the confirm() method) returns true if the user clicks “OK”, and false on “Cancel”.
The idea behind the confirmation box is to prevent access to the page before clicking and closing the box.
For example:
confirm("Do you want to continue?");
Output:
3. Prompt Box
The prompt box displays a modal with a message that asks a user to enter text input.
To create a prompt box in JavaScript, use the built-in prompt() method. This method takes two arguments:
- The text to be displayed.
- The optional default text to the input field.
The prompt box (the prompt() method) returns the text entered by the user as a string. If no text was entered, a null is returned.
Here is an example use:
prompt("Enter a name you want to be called on the site: ", "Charlie");
Output:
Conclusion
Today you learned the three types of popup boxes in JavaScript.
To recap:
- Use an alert box by calling the alert() method to display a warning/message.
- Use a confirmation box by calling the confirm() method to display a confirmation message.
- Use a prompt box by calling the prompt() method to ask for user input before continuing on the page