JS use event to prevent bubbles to achieve click on the blank modal box hidden _javascript skills

Source: Internet
Author: User
Many times, we do the front end when there is such a small function, click to pop a box, but, sometimes do not want to operate, want to click on a blank, hide the box. Assuming the following scene, a small button, click Can pop a modal box.

It's so simple, but we want to click on the blank part of the time to hide the modal box, add button id:btn, modal box Id:model

Perhaps our simplest idea is to listen to an event directly on the document, pseudocode as follows:

button click Pop-up Event Monitor:
Copy Code code as follows:

$ ("#btn"). Bind ("click", Function (e) {
if (e.stoppropagation) {//need to block bubbling
E.stoppropagation ();
}else{
E.cancelbubble = true;
}
})

Copy Code code as follows:

$ (document). Bind ("click", Function (e) {
If (click event is not on model) {
Hidden modal box;
}
})

At first glance, this is no problem, but, in fact, there are many problems, first of all, we must pay attention to prevent bubbling, otherwise, click on the button, actually triggered the above two events, modal is not bouncing out, is actually bouncing out, and immediately hidden, and, when we have many small controls on the modal box, We can hardly judge the clicks in the Modal box.

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

First, the modal box listens for an event as follows:
Copy Code code as follows:

$ ("#modal"). Bind ("click", Function (event) {
if (event && event.stoppropagation) {
Event.stoppropagation ();
} else {
Event.cancelbubble = true;
}

});

Simply blocks the click event Bubbling in the Modal box,

And then:
Copy Code code as follows:

$ (document). One ("click", Function (e) {
var $target = $ (e.currenttarget);
if ($target. attr ("id")!= "modal") {
$ ("#modal"). CSS ("display", "none");
}
});

It's easy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.