简体   繁体   中英

jQuery - Closing modal pop-up by clicking outside of it not working

I'm trying to close a pop-up when clicking outside of it.

HTML

<span class="open"data-modal="modal1">Button</span>

<div class="modal" id="modal1">

    <!--modal content-->
    <div class="modal-content">

        <!--close button-->
        <span class="close">&times;</span>

        <!--content-->

    </div>
</div>

JS

$(document).ready( function() {

    //open pop-up when span is clicked
    $(".open").on("click", function() {
        var modalId = $(this).data("modal");
        var $modal = $("#" + modalId);
        $modal.show();
    });

    //close pop-up when close button is clicked
    $(".close").on("click", function() {
        $(this).closest(".modal").hide();
    });



    $("body").click(function(){
        $(".modal").hide();
    });

    // Prevent events from getting pass .popup
    $(".modal-content").click(function(e){
       e.stopPropagation();
    });

});

At the bottom of that code block, I have a click function on the body that hides the modal, but if modal-content is clicked, then e.stopPropagation(); is fired.

However, when I click the button to open the pop-up, it doesn't open because of $("body").click(function(){} .

Is there a way I can wrap $("body").click(function(){} in something like:

if($('.modal').show == true{ ... });

Yes, you could do it like this:

$("body").click(function() {
   if ($(".modal").is(":visible")) {
       $(".modal").hide();
   }
});

All you need to do is the same you already did before, this is to stop the propagation when you click the open button:

//open pop-up when span is clicked
$(".open").on("click", function(e) { //with event now
    e.stopPropagation(); //stopping propagation here
    var modalId = $(this).data("modal");
    var $modal = $("#" + modalId);
    $modal.show();
});

So that it doesn't then call the hide() on the body click handler.

Using bootstrap 4, you can close modal when clicking outside by just doing this.

 $('.modal').click(function (e) {
    $('.modal').modal('toggle');
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM