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 returntrue
. - 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?
- Quick Decisions: If you want a quick decision from the user, like "Are you sure you want to delete this?".
- Simple Confirmation: Before taking actions that can't be easily undone.
Limitations
- Look & Feel: The design of the dialog box cannot be changed. It looks different in different browsers.
- Single Option: Only gives "OK" and "Cancel" options. You can't add more buttons or customize their names.