How To Hide Modal In Jquery

In this tutorial, you will learn how to hide a modal using jQuery. A modal is a dialog box or popup window that is displayed on the current page, usually to display additional content or to prompt the user for input.

To get started, you will need to include the jQuery library in your HTML file. You can do this by adding the following script tag to your HTML:

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

Creating a modal

First, let’s create a simple modal with an “OK” button. Add the following HTML to your page:

<div id="myModal" class="modal">
  <div class="modal-content">
    <p>This is a simple modal!</p>
    <button id="okButton">OK</button>
  </div>
</div>

Hiding the modal

To hide the modal, you can use the hide() method in jQuery. Add the following script tag to your HTML file:

<script>
  $(document).ready(function() {
    // Hide the modal when the "OK" button is clicked
    $("#okButton").click(function() {
      $("#myModal").hide();
    });
  });
</script>

The code above will hide the modal when the “OK” button is clicked. You can also hide the modal by clicking outside of it. To do this, add the following code inside the $(document).ready() function:

$(document).click(function(event) {
  // If the target element is not inside the modal, hide the modal
  if (!$(event.target).closest('.modal-content').length) {
    $("#myModal").hide();
  }
});

Complete example

Here’s the complete example with everything put together:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>How to Hide a Modal in jQuery</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="myModal" class="modal">
    <div class="modal-content">
      <p>This is a simple modal!</p>
      <button id="okButton">OK</button>
    </div>
  </div>

  <script>
    $(document).ready(function() {
      // Hide the modal when the "OK" button is clicked
      $("#okButton").click(function() {
        $("#myModal").hide();
      });

      // Hide the modal when clicking outside of it
      $(document).click(function(event) {
        if (!$(event.target).closest('.modal-content').length) {
          $("#myModal").hide();
        }
      });
    });
  </script>
</body>
</html>

Now you know how to hide a modal using jQuery. By using the methods demonstrated above, you can easily create responsive and user-friendly modals on your web pages.