How to create a delete confirmation modal with CSS and JavaScript?


To create a delete confirmation modal with CSS and JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: Arial, Helvetica, sans-serif;
   }
   .modal {
      text-align: center;
      display: none;
      position: fixed;
      z-index: 1;
      padding-top: 100px;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
   }
   .modalContent {
      font-size: 20px;
      font-weight: bold;
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
   }
   .close {
      color: rgb(255, 65, 65);
      float: right;
      font-size: 40px;
      font-weight: bold;
   }
   .close:hover, .close:focus {
      color: #ff1010;
      cursor: pointer;
   }
   .modalContent button {
      border: none;
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      padding: 10px;
   }
   .del {
      background-color: rgb(255, 65, 65);
   }
   .del:hover {
      background-color: rgb(255, 7, 7);
   }
   .cancel:hover {
      background-color: rgb(167, 167, 167);
   }
</style>
</head>
<body>
<h1>Modal Example</h1>
<button class="openModal">Open Modal</button>
<h2>Click on the above button to open modal</h2>
<div class="modal">
<div class="modalContent">
<span class="close">×</span>
<p>Are you sure you want to delete your account</p>
<button class="del" onclick="hideModal()">Delete Account</button>
<button class="cancel" onclick="hideModal()">Cancel</button>
</div>
</div>
<script>
   var modal = document.querySelector(".modal");
   var btn = document.querySelector(".openModal");
   var span = document.querySelector(".close");
   btn.addEventListener("click", () => {
      modal.style.display = "block";
   });
   span.addEventListener("click", () => {
      hideModal();
   });
   function hideModal() {
      modal.style.display = "none";
   }
   window.onclick = function(event) {
      if (event.target == modal) {
         hideModal();
      }
   };
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the Open Modal button −

Updated on: 07-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements