confirm ExamplesΒΆ

The general syntax for this method is:

let answer = window.confirm("Message to user");

Displays a dialog box with a message and returns true if user clicks "ok" and false if user clicks "cancel". The browser waits until the user clicks "ok" or "cancel".

Example

let response = window.confirm("Would you like to play a game?");
// Code does NOT continue until user responds to confirm window
if (response) {
   console.log("Let's play a board game");
} else {
   console.log("Oh well, let's code instead");
}

Note

Remember that methods defined on window can be used without referencing the window variable.

Example

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>DOM Examples</title>
 5   </head>
 6   <body>
 7      <h1>Window Confirm Example</h1>
 8      <script>
 9            let response = confirm("Are you excited?");
10            if (response) {
11               console.log("Yay! Me too!");
12            } else {
13               console.log("Oh no! I hope tomorrow is a better day!");
14            }
15      </script>
16   </body>
17</html>

Console Output (If "cancel" clicked)

Oh no! I hope tomorrow is a better day!