Many times, when we are working on the front end, we will have such a small function. Click to pop up a certain box. However, sometimes we don’t want to operate, so we want to click on a blank space to hide the box. Assume the following scenario, a small button can pop up a modal box when clicked.
It’s that simple, but we want to hide the modal box when clicking on the blank part, add button id: btn, modal box id: model
Perhaps our simplest idea is to directly Listen for an event on the document. The pseudo code is as follows:
Button click pop-up event monitoring:
$("#btn").bind("click",function(e){
if(e.stopPropagation){//Need to prevent bubbling
e .stopPropagation();
}else{
e.cancelBubble = true;
}
})
$(document).bind("click",function(e){
if (the click event is not on the model) {
Hide modal box;
}
})
At first glance, this is no problem, but in fact, there are many problems. First, we have to pay attention to blocking Bubble, otherwise, clicking the button actually triggers the above two events. The modal cannot pop up. In fact, it pops up and is hidden immediately. Moreover, when we have many small controls on the modal box, Sometimes, it is difficult for us to judge the click in the modal box.
Here, I think there is one of the most classic methods, which is 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;
}
});
Simply prevent click events from bubbling up in the modal,
Then:
$(document).one("click", function(e){
var $target = $(e.currentTarget);
if ( $target.attr("id") != "modal") {
$("#modal").css("display", "none");
}
});
Done, so easy