BOM Popup Alert (Popup Boxes)

JavaScript has three kind of popup boxes:

  1. Alert box
    1. Confirm box
    1. Prompt box

Alert Box

An alert box is generally used if 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("write something");

The window.alert() method can be used without the window prefix.

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>Alert Box</h2>

<button onclick="myFunc()">Click me</button>

<script>
function myFunc() {
  alert("My alert box!");
}
</script>

</body>
</html>

Output (Before Click):-

Output (After Click):-


Confirm Box

A confirm box is generally used to verify or accept something.

When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed.

If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns false.

window.confirm("My confirm box");

The window.confirm() method can be written without the window prefix.

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>Confirm Box</h2>


<button onclick="myFunc()">Click me</button>

<p id="result"></p>

<script>
function myFunc() {
  var res;
  if (confirm("Press a button!")) {
    res = "You pressed OK!";
  } else {
    res = "You pressed Cancel!";
  }
  document.getElementById("result").innerHTML = res;
}
</script>

</body>
</html>

Output (Before click the button):-

Output (After click the button):-

Output (After pressed OK in confirm box):-


Prompt Box

A prompt box is generaly used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.

If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the box returns null.

window.prompt("myText","defaultText");

The window.prompt() method can be written without the window prefix.

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>Prompt Box</h2>

<button onclick="myFunc()">Click me</button>

<p id="result"></p>

<script>
function myFunc() {
  var res;
  var user = prompt("Please enter your name:", "John Doe");
  if (user == null || user == "") {
    res = "User cancelled the prompt.";
  } else {
    res = "Hello " + user + "! How are you?";
  }
  document.getElementById("result").innerHTML = res;
}
</script>

</body>
</html>

Output (Before click the button):-

Output (After click the button):-

Output (After pressed OK in prompt box):-


Line Breaks

To display line breaks inside a popup box, use a back-slash followed by the character \n.

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>Line Break popup box.</h2>

<button onclick="alert('Hello\nHow are you?')">Click me</button>

</body>
</html>

Output (Before click):-

Output (After click):-