How to Use "window.confirm()"

What is window.confirm()?

window.confirm() is a simple way to show a pop-up dialog to the user, asking them a yes/no question. It's a part of the web browser's built-in JavaScript functions.

When it runs, it pauses the code and waits for the user to respond.

It can be super useful to catch a user in the middle of something that might want confirmation before they continue.

How to use it?

To use window.confirm(), you write:

let userResponse = confirm("Do you want to continue?");

Note: window is inferred, so you don't need to explicitly use window.confirm().

This code will show a dialog box with the message "Do you want to continue?". The user will have "OK" and "Cancel" buttons.

  • If the user clicks "OK", window.confirm() will return true.
  • If the user clicks "Cancel", it will return false.

You can then use this true or false value to decide what to do next in your code:

if (userResponse) {
    // The user clicked "OK"
} else {
    // The user clicked "Cancel"
}

Here's an example of it in action:

When to use it?

  1. Quick Decisions: If you want a quick decision from the user, like "Are you sure you want to delete this?".
  2. Simple Confirmation: Before taking actions that can't be easily undone.

Limitations

  1. Look & Feel: The design of the dialog box cannot be changed. It looks different in different browsers.
  2. Single Option: Only gives "OK" and "Cancel" options. You can't add more buttons or customize their names.
JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.