JavaScript Pop Ups


Pop Up Windows

Popups in javascript are used to interact with users either by displaying some data or by taking some kind of input from the user.

The way these three popup windows look is determined by different kinds of browsers. These boxes can't be modified by CSS.

In javascript, there are 3 different kinds of pop-ups. All 3 have different purposes:

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

Let's see all three types of popups and their use.


1. Alert Box In Javascript

The alert box displays small messages. It contains one OK button.

To create an alert box use alert() method, which is a global method. Execution of the javascript code below the alert code is stopped until the OK button is clicked.

The following example shows how to display messages using an alert box.

Example

alert("This is a direct string alert message");

var message = "This is variable string";
alert(message);
Try it

2. Confirm Box In Javascript

The confirm box is used to interact with users. It takes input from the user in form of confirmation of whether a task should be performed or not.

The confirm box contains two buttons OK and Cancel. The OK button is used to confirm the action and the Cancel button is used to cancel the action.

Also, you can pass a message to the confirm box to display it to the user.

The confirm box is similar to an alert box but it can return a boolean value, which is used to know what was action taken by the user for the confirmation.

Example

var del = confirm("Do you want to delete the file?");
if (del) {
  console.log("File Deleted!");
}
else {
  console.log("File Not Deleted!");
}
Try it

3. Prompt Box In Javascript

The prompt box is another popup box in javascript which allows the user to take input in form of a string.

The prompt box contains an input field where the user can enter the input. Which is then returned by the prompt box as a string.

The following example will take two inputs from the user and will print their sum.

Example

// taking inputs
var num1 = prompt("Enter 1st number:");
var num2 = prompt("Enter 2nd number:");

// String to integer conversion
num1 = parseInt(num1);
num2 = parseInt(num2);

var sum = num1 + num2;
console.log("Sum = " + sum);
Try it

Note: When a dialogue box appears the javascript stops execution of code below the box code until the box is closed.