JavaScript Popup Boxes

JavaScript Popup Boxes

In JavaScript, there are three types of popup boxes:

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

Here is the syntax for using each of them:

// Alert
window.alert("something");

// Confirm
window.confirm("something");

// Prompt
window.prompt("something", "default text");

In this guide, you learn what these popups do and how to use them.

JavaScript Popup Modals

Alert Box

In JavaScript, you can message or warn a user with an alert box. When a user sees an alert box, they have to click “OK” to proceed.

You can create an alert box with the built-in alert() method. This method takes one argument which is the alert message to be displayed.

Here is an example of how to create an alert box in JavaScript:

alert("Enable JavaScript to Continue on the Site!");

Output:

Alert Box in JavaScript

Confirmation Box

The confirmation popup box is used to display a dialog with a message and two buttons, “OK” and “Cancel”.

To create a confirmation box, use the built-in confirm() method. This method takes one argument which specifies the confirmation message to be displayed.

The confirmation box (the confirm() method) returns true if the user clicks “OK”, and false on “Cancel”.

The idea behind the confirmation box is to prevent access to the page before clicking and closing the box.

For example:

confirm("Do you want to continue?");

Output:

Prompt Box

The prompt box displays a modal with a message that asks a user to enter text input.

To create a prompt box in JavaScript, use the built-in prompt() method. This method takes two arguments:

  1. The text to be displayed.
  2. The optional default text to the input field.

The prompt box (the prompt() method) returns the text entered by the user as a string. If no text was entered, a null is returned.

Here is an example use:

prompt("Enter a name you want to be called on the site: ", "Charlie");

Output:

Conclusion

Today you learned the three types of popup boxes in JavaScript.

To recap:

  • Use an alert box by calling the alert() method to display a warning/message.
  • Use a confirmation box by calling the confirm() method to display a confirmation message.
  • Use a prompt box by calling the prompt() method to ask user input before continuing on the page

Thanks for reading.

Happy coding!

Further Reading

100 JavaScript Interview Questions

50+ Web Development Buzzwords

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.