close

How to make modal close on click outside

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to make modal close on click outside in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to make modal close on click outside ?

  1. How to make modal close on click outside ?

    to make modal close on click outside This is not the most efficient way, but it will work. The idea is to traverse the tree and check if the parent is the id of the one where you don't want to hide on click anywhere except it.

  2. How to make modal close on click outside ?

    to make modal close on click outside This is not the most efficient way, but it will work. The idea is to traverse the tree and check if the parent is the id of the one where you don't want to hide on click anywhere except it.

Method 1


Use the parent node #openModal (container) instead of #popUpForm (form) :

$('body').click(function (event) 
{
   if(!$(event.target).closest('#openModal').length && !$(event.target).is('#openModal')) {
     $(".modalDialog").hide();
   }     
});

Method 2

This is not the most efficient way, but it will work. The idea is to traverse the tree and check if the parent is the id of the one where you don’t want to hide on click anywhere except it.

$(document).on('click', function(e) {    
    var p = e.target;
    while(p) {
        console.log(p);
        if(p.id) {
            if(p.id == 'openModal') {
                return;
            }
        }
        p = p.parentElement;
    }
    $("#openModal").hide();
});

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment