JavaScript Popup Boxes

In JavaScript, there are three types of popup boxes:

  1. Alert Box.
  2. Confirm Box.
  3. Prompt Box.

Here is the syntax for using each of them:

// Alert

// Confirm

// 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:

NameUse CaseExample
1. Alert BoxWarn userswindow.alert(“Too many windows open!“);
2. Confirmation BoxAsk for user confirmation before accessing the pagewindow.confirm(“Do you want to proceed?“);
3. Prompt BoxAsk for the user inputwindow.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!");


Alert Box in JavaScript

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?");


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:

  1. The text to be displayed.
  2. 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");



Today you learned the three types of popup boxes in JavaScript.

To recap:

  1. Use an alert box by calling the alert() method to display a warning/message.
  2. Use a confirmation box by calling the confirm() method to display a confirmation message.
  3. Use a prompt box by calling the prompt() method to ask for user input before continuing on the page

Thanks for reading.

Happy coding!

Further Reading