Using JavaScript Confirm Dialog [Window.confirm()] Tutorial

In this article, we will tackle about Using the JavaScript Confirm Dialog. This tutorial aims to provide IT/CS students and new programmers with a reference for understanding the use of the Window.confirm() function of JavaScript. Here, sample snippets and sample source code zip file that demonstrates our object for this article are provided and are free to download.

What is Confirm Dialog [Window.confirm()]?

The Confirm Dialog [Window.confirm()] is one of the built-in instance methods of JavaScript. It allows the developer to implement a decisional dialog in the client side which ask the end-user whether to continue or discontinue to process the certain action or execution.

How does the Confirm Dialog [Window.confirm()] work?

The browser is told to display a dialog box with an optional message when the confirm function is used, and to wait until the user confirms or cancels the dialog box. For example, in an application, there is a delete data feature that can be triggered by clicking a button and the button has a confirmation feature using Window.confirm(). Using the confirm method, the developer can prevent data loss due to accidentally deleted by asking first the user whether to continue the deletion or not.

Syntax

  1.         confirm("Confirm Dialog's Message Here");
  2.    

Parameters

Message

This parameter contains the message to be shown or displayed in the dialog.

Return Value

The Window.confirm() instance method/function returns a boolean (true/false) value. The "Ok" button will return true and the "Cancel" button returns false.

Example

Here are some snippets that demonstrate how to use confirm instance method of JavaScript in your web application

Interface

The following snippet is an HTML snippet for the page interface. It contains 2 different buttons that both triggers a Window.confirm() function. The result of the execution of confirm method for both the Ok and Cancel buttons in the dialog will be shown in the HTML <pre> tag. Save the file as index.html.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>JavaScript Confirm Dialog</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.  
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12.  
  13.     <style>
  14.         html, body{
  15.             height: 100%;
  16.             width: 100%;
  17.         }
  18.         body{
  19.             display: flex;
  20.             height: 100%;
  21.             width: 100%;
  22.             flex-direction: column;
  23.         }
  24.         body>nav, body>footer{
  25.             flex-shrink: 1;
  26.         }
  27.         body>main{
  28.             flex-shrink: 1;
  29.             flex-grow: 1;
  30.             overflow: auto;
  31.             display: flex;
  32.             flex-direction: column;
  33.             width: 100%;
  34.             align-items: center;
  35.             justify-content: center;
  36.         }
  37.         pre{
  38.             min-height:20vh
  39.         }
  40.     </style>
  41. </head>
  42. <body style="background:#eff3fc">
  43.     <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
  44.         <div class="container">
  45.             <a class="navbar-brand" href="./">JavaScript Confirm Dialog</a>
  46.             <div>
  47.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  48.             </div>
  49.         </div>
  50.     </nav>
  51.  
  52.     <main class="container-fluid">
  53.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  54.             <h2 class="text-center">Using JavaScript Confirm Dialog (Window.confirm())</h2>
  55.             <hr>
  56.  
  57.             <div class="card mt-3 rounded-0">
  58.                 <div class="card-body rounded-0">
  59.                     <div class="container-fluid">
  60.                         <div class="row justify-content-center">
  61.                             <div class="col-lg-4 col-lg-5 col-sm-6">
  62.                                 <button class="btn btn-primary rounded-pill w-100" type="button" id="trigger1">Trigger Confirm 1</button>
  63.                             </div>
  64.                             <div class="col-lg-4 col-lg-5 col-sm-6">
  65.                                 <button class="btn btn-warning rounded-pill w-100" type="button" id="trigger2">Trigger Confirm 2</button>
  66.                             </div>
  67.                         </div>
  68.                     </div>
  69.                 </div>
  70.             </div>
  71.             <div class="card mt-3 rounded-0">
  72.                 <div class="card-body rounded-0">
  73.                     <div class="container-fluid">
  74.                         <label for="" class="fw-bolder">Result</label>
  75.                         <div class="clear-fix py-1"></div>
  76.                         <pre class="bg-dark text-white px-2 py-3"></pre>
  77.                     </div>
  78.                 </div>
  79.             </div>
  80.         </div>
  81.     </main>
  82. <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
  83.     <div class="container-fluid my-2">
  84.         <div class="text-center">
  85.             <b>JavaScript Confirm Dialog &copy; 2022</b>
  86.         </div>
  87.     </div>
  88. </footer>
  89. </body>
  90. <script src="script.js"></script>
  91. </html>

JavaScript

Here's the snippet of the JavaScript File that contains the scripts for executing confirm dialog [window.confirm()] when the 2 buttons on the page are clicked. Save the file as script.js.

  1. /**
  2. * Trigger 1 Button
  3. * Click Event Listener
  4. * Sample Confirm Dialog Script #1
  5. */
  6.  
  7. document.getElementById('trigger1').addEventListener('click', function(e){
  8.     e.preventDefault()
  9.  
  10.     // Confirm Dialog w/ message
  11.     var _confirm = confirm(`This is a sample Confirm Dialog Message.`)
  12.  
  13.     if(_confirm === true){
  14.         /**
  15.         * User has clicked the OK Button in the Dialog.
  16.         * - Wtite Something Here
  17.         */
  18.         document.querySelector('pre').innerHTML = JSON.stringify({trigger: "Sample Confirm Dialog #1", user_action:"User has clicked the Ok Button"}, null, 3)
  19.     }else{
  20.         document.querySelector('pre').innerHTML = JSON.stringify({trigger: "Sample Confirm Dialog #1", user_action:"User has clicked the Cancel Button"}, null, 3)
  21.     }
  22. })
  23.  
  24. /**
  25. * Trigger 2 Button
  26. * Click Event Listener
  27. * Sample Confirm Dialog Script #2
  28. */
  29.  
  30. document.getElementById('trigger2').addEventListener('click', function(e){
  31.     e.preventDefault()
  32.  
  33.     // Confirm Dialog w/ message
  34.     var _confirm = confirm(`Are you sure to continue the process.`)
  35.  
  36.     if(_confirm === true){
  37.         /**
  38.         * - Write Something Here
  39.         */
  40.         TestFunc();
  41.     }else{
  42.         document.querySelector('pre').innerHTML = JSON.stringify({trigger: "Sample Confirm Dialog #2", user_action:"User has clicked the Cancel Button"}, null, 3)
  43.     }
  44. })
  45.  
  46. window.TestFunc = function(){
  47.     document.querySelector('pre').innerHTML = `Processing...`
  48.     var i = 1
  49.     var testInterval = setInterval(()=>{
  50.         document.querySelector('pre').innerHTML += `<br>Sample Progress ${i}...`
  51.         if(i == 5){
  52.             document.querySelector('pre').innerHTML += `<br>Done.`
  53.             clearInterval(testInterval);
  54.         }
  55.         i++;
  56.     },1000)
  57.  
  58. }

The "Trigger Confirm 2" event listener above triggers to execute a process of function if the user will choose the "OK" button which demonstrates the confirmation feature of action before execution.

Snapshots

As a result, the snippets that I provided above output the following images.

Page Interface

JS confirm DEMO App

Button 1 Confirm Dialog

JS confirm DEMO App

"Ok" Button Result

JS confirm DEMO App

"Cancel" Button Result

JS confirm DEMO App

There you go! That's the end of this tutorial. I have provided a working web application source code zip file of the snippet I created and provided above. You can download it by clicking the Download button located below this article.

I hope this JavaScript Confirm Dialog [Window.confirm()] Tutorial helps you with what you are looking for and you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment