Js uses event blocking and bubbling to hide the blank modal box

Source: Internet
Author: User

Click a box to pop up, but sometimes you don't want to operate it. You just want to click a blank space to hide the box. The following is a specific implementation:

Most of the time, we have such a small function when doing front-end operations. Click a box to pop up. However, if you don't want to operate it, you just want to click a blank space to hide the box. In the following scenario, click a small button to bring up a modal box. This is simple, but we want to hide the modal box when you click the blank part. Add the button id: btn and the modal box id: the simplest idea of model is to directly listen to an event on the document. The pseudocode is as follows: click the button to display the event listener: the code is as follows: $ ("# btn "). bind ("click", function (e) {if (e. stopPropagation) {// You Need To prevent bubbling e. stopPropagation ();} else {e. cancelBubble = true ;}}) the code is as follows: $ (document ). bind ("click", function (e) {if (click event not on model) {hide modal box;}) at first glance, this is okay,, in fact, there are many problems. First, we have to prevent bubbles. Otherwise, clicking the button actually triggers the above two events. modal cannot be played, but it actually pops up, it was immediately hidden, and when we had a lot When using the widget, it is difficult to determine the click in the modal box. Here, I think there is a classic method, which is simple but clever. First, listen to an event for the modal box as follows: $ ("# modal "). bind ("click", function (event) {if (event & event. stopPropagation) {event. stopPropagation ();} else {event. cancelBubble = true ;}}); simply prevents click events from bubbling in the modal box. Then, 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

Related Article

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.