Popup Alert

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

window.alert(), window.prompt(), window.confirm()

Global functions are methods of the global object so you can use without using the prefix window. It means alert('Watch out!') and window.alert('Watch out!') are exactly the same.

window.alert()

It is not an ECMAScript function, but a BOM method. When an alert box pops up, the user will have to click "OK" to proceed.

snippet
alert("I am an alert box!");

You cannot interact with user. In addition to it, two other BOM methods allow you to interact with the user through system messages.

window.confirm()

A confirm box is often used if you want the user to verify or accept something. It gives the user two options—OK and Cancel. If the user clicks "OK", the box returns true. If the user clicks "Cancel" or closing the message using the X icon (or the ESC key) returns false.

snippet
var result = confirm("Press a button");
if (result) //true {
    console.log("You pressed OK!");
}
else {
    console.log("You pressed Cancel!");
}

if (confirm('Are you sure you want to delete this item?')) {
    // delete
} else {
    // abort
}
window.prompt()

A prompt box collects textual input. window.prompt() presents the user with a dialog to enter text. It returns the following value based on user interaction.

ValuesDescription
nullif you click Cancel or the X icon, or press ESC
"" (empty string)you click OK or press Enter without typing anything
A text stringif you type something and then click OK (or press Enter)
snippet
var answer = prompt('And your name was?'); 
console.log(answer);

The function also takes a string as a second parameter and displays it as a default value pre-filled into the input field.

snippet
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    console.log(person);
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +