简体   繁体   中英

How to close own modal on outside click?

I have made modal window. It closes by clicking on X button. But now I want to close it, if user click of modal outside area.

    $("a[href='#modal']").click(function(e) {
        e.preventDefault();
        $("body").addClass("noscroll");
        $(".modal").addClass("is-active");
        $(".modal_overlay").addClass("is-active");
    });
    $(".modal .close").click(function(e) {
        e.preventDefault();
        if($(".modal").hasClass("is-active")) {
            $("body").removeClass("noscroll");
            $(".modal").removeClass("is-active");
            $(".modal_overlay").removeClass("is-active");
        }
    });

Here's a solution:

function close(){
    $("body").addClass("noscroll");
    $(".modal").addClass("is-active");
    $(".modal_overlay").addClass("is-active");
}
$("a[href='#modal']").click(function(e) {
    e.preventDefault();
    close();
});
$(".modal .close").click(function(e) {
    e.preventDefault();
    if($(".modal").hasClass("is-active")) {
        close();
    }
});
$(window).click(function(e) {
       close();
       return false;
});
$(".modal").click(function(){
    return false; // prevents a click in dialog to close the modal
});

It just handles the click on the window to close the modal, while intercepting them in the modal to prevent them from hitting the previous event handler.

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