How To Modal Close In Jquery

Modal dialogs are a popular way to display additional content on a web page without navigating away from the current view. In this blog post, we will discuss how to close a modal dialog using jQuery.

Prerequisites

Before we start, make sure you have the following prerequisites:

  • Basic understanding of HTML, CSS, and JavaScript
  • jQuery library included in your project

Creating a Simple Modal

First, let’s create a simple modal with some HTML and CSS. We will have a button to open the modal, and a close button within the modal to close it.

Here is the HTML structure:

<div class="modal" id="myModal">
    <div class="modal-content">
        <span class="close">&#215;</span>
        <h2>My Modal</h2>
        <p>This is a simple modal dialog.</p>
    </div>
</div>

<button id="openModal">Open Modal</button>

And the CSS to style the modal:

.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.4);
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

Using jQuery to Close the Modal

Now that we have our modal and close button, let’s use jQuery to close the modal when the close button is clicked. We will also close the modal when the user clicks outside of the modal content.

First, add the following jQuery code to your JavaScript file or within <script> tags on your HTML page:

$(document).ready(function(){
    // Get the modal
    var modal = $('#myModal');

    // Get the close button
    var closeButton = $('.close');

    // When the user clicks the close button, close the modal
    closeButton.on('click', function() {
        modal.hide();
    });

    // When the user clicks anywhere outside of the modal content, close the modal
    $(window).on('click', function(event) {
        if ($(event.target).is(modal)) {
            modal.hide();
        }
    });
});

Additionally, you can add an event listener to the open button to display the modal when clicked:

$('#openModal').on('click', function() {
    modal.show();
});

Conclusion

In this blog post, we demonstrated how to close a modal using jQuery. We created a simple modal and close button, and then used jQuery to close the modal when the close button is clicked, or when the user clicks outside of the modal content. This technique can be easily adapted for more complex modals or integrated into existing projects.