Skip to main content

JavaScript Popup

JavaScript popup boxes are a way to display messages, alerts, or prompts on a web page.

There are three types of popup boxes in JavaScript:

Alert box​

An alert box is used to display a message to the user. It is a simple dialog box with a message and an OK button. To create an alert box, you can use the alert() function in JavaScript.

As an example:

alert("Hello World!");

Confirm box​

A confirm box is used to ask the user for confirmation before proceeding with an action. It is a dialog box with a message, a OK button, and a Cancel button. To create a confirm box, you can use the confirm() function in JavaScript.

As an example:

if (confirm("Are you sure you want to delete this item?")) {
// Delete the item
} else {
// Do nothing
}

Prompt box​

A prompt box is used to ask the user to enter some information. It is a dialog box with a message, an input field, an OK button, and a Cancel button. To create a prompt box, you can use the prompt() function in JavaScript.

As an example:

let name = prompt("Please enter your name:", "John Doe");
if (name != null) {
alert("Hello, " + name + "!");
}
tip

Popup boxes can be annoying for users if overused, so it's important to use them sparingly and only when necessary.

Line Breaks​

The line breaks can be added using the newline character (\n) or the HTML <br> tag.

Using the newline character​

To add a line break in a JavaScript popup box, you can use the newline character (\n) to separate lines of text.

As an example:

alert("Hello,\nWorld!");

Output:

Hello,
World!

Using the <br> tag​

You can also use the HTML <br> tag to add line breaks in a JavaScript popup box. However, you need to create a string of HTML code using backticks or quotation marks to include the tag.

As an example:

alert("Hello,<br>World!");

Output:

Hello,
World!