Jquery modal

by pj_js15

HTML

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <button id="showModalBtn">Open Modal</button>
  <div id="modal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <p>This is a modal window.</p>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="script.js"></script>
</body>
</html>

CSS

.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #fff;
  margin: 20% auto;
  padding: 20px;
  width: 60%;
  border-radius: 5px;
  position: relative;
}

.close {
  position: absolute;
  top: 0;
  right: 0;
  padding: 10px;
  cursor: pointer;
}

/* Style the button to look like a link */
#showModalBtn {
  text-decoration: underline; /* Underline the link text */
  color: blue; /* Set the link text color to blue */
  cursor: pointer; /* Change the cursor to a pointer on hover for better user experience */
  background: none;
  border: none;
}

JavaScript

$(document).ready(function() {
  // Open modal when the button is clicked
  $("#showModalBtn").click(function() {
    $("#modal").show();
  });

  // Close modal when the close button or outside the modal is clicked
  $(".close, .modal").click(function() {
    $("#modal").hide();
  });

  // Prevent modal from closing when clicking inside the modal content
  $(".modal-content").click(function(event) {
    event.stopPropagation();
  });
});