Js USES the event to prevent bubbling to achieve the hidden click of the blank modal box

  • 2020-03-30 01:29:28
  • OfStack

A lot of times, when we do the front end will have this little function, click to pop up a box, but sometimes, don't want to operate, just want to click on a blank, hide the box. Suppose the following scenario, a small button, click to pop up a modal box.

It's as simple as that, but we want to hide the modal box when we click on the blank, add the button id: BTN, and the modal box id: model

Perhaps our simplest idea is to directly listen for an event on the document. The pseudo-code is as follows:

Click the button to click the pop-up event monitor:
 
$("#btn").bind("click",function(e){ 
if(e.stopPropagation){//We need to stop the bubbling
e.stopPropagation(); 
}else{ 
e.cancelBubble = true; 
} 
}) 

 
$(document).bind("click",function(e){ 
if( Click event not in model on ){ 
 Hide the modal box ; 
} 
}) 

At first glance, it is no problem, however, there are a lot of problems, first of all, we must pay attention to prevent a bubble, otherwise, click on the button, actual it is triggered, the above two events modal is play not to come out, actually is playing out, immediately hide again, and, when we are on the modal dialog and many small controls, we in the modal dialog click it is difficult to judge.

Here, I think, is one of the most classic methods, very simple, but very clever,

First, listen for an event for the modal box as follows:
 
$("#modal").bind("click", function(event) { 
if (event && event.stopPropagation) { 
event.stopPropagation(); 
} else { 
event.cancelBubble = true; 
} 

}); 

It simply prevents the click event from bubbling in the modal box,

And then:
 
$(document).one("click", function(e){ 
var $target = $(e.currentTarget); 
if ($target.attr("id") != "modal") { 
$("#modal").css("display", "none"); 
} 
}); 

That's it, so easy

Related articles: