HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Popup Boxes

JavaScript provides three kinds of popup boxes: **Alert**, **Confirm**, and **Prompt**. These are built into the browser and allow you to quickly show information to the user or ask for their input without creating custom HTML modals.


Interactive Popup Lab

Try the different types of popup boxes below and see what value they return to JavaScript:


1. Alert Box

An alert box is used when you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.

window.alert("I am an alert box!");

// You can also skip 'window'
alert("Hello World!");

2. Confirm Box

A confirm box is used when you want the user to verify or accept something. It returns true if the user clicks "OK", and false if they click "Cancel".

let result = confirm("Press a button!");

if (result == true) {
    console.log("You pressed OK!");
} else {
    console.log("You pressed Cancel!");
}

3. Prompt Box

A prompt box is used if you want the user to input a value before entering a page. It returns the input string if they click "OK", or null if they click "Cancel".

let person = prompt("Please enter your name:", "Guest");

if (person != null && person != "") {
    console.log("Hello " + person + "!");
}
Note: The second parameter in prompt() is the default value shown in the input field.

Line Breaks in Popups

To display line breaks inside a popup box, use a backslash followed by the character 'n' (\n).

alert("Hello\nHow are you today?");

Popup Methods Summary

Box Type Use Case Return Value
alert() Show simple info/warning Undefined
confirm() Ask for user confirmation Boolean (true/false)
prompt() Ask for text input String or null
Important: Popup boxes are "modal" — they prevent the user from accessing the rest of the web page until the box is closed. Overusing them results in a poor user experience.

Key Points to Remember

  • Use alert() for critical messages that must be seen.
  • Use confirm() for dangerous actions like "Delete Account".
  • Use prompt() sparingly; it's often better to use HTML forms.
  • All three methods pause JavaScript execution until the user responds.
  • You can add \n to create multi-line messages.