Home  >  Article  >  Web Front-end  >  js uses the event to prevent bubbling to hide the click blank modal box_javascript skills

js uses the event to prevent bubbling to hide the click blank modal box_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:02:391065browse

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:

Copy code Code As follows:

$("#btn").bind("click",function(e){
if(e.stopPropagation){//Need to prevent bubbling
e .stopPropagation();
}else{
e.cancelBubble = true;
}
})

Copy the code The code is as follows:

$(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:
Copy code The code is 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:
Copy code The code is as follows:

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

Done, so easy
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn