Click on the page to hide Div__javascript other places

Source: Internet
Author: User
Click elsewhere on the page to hide the jquery delegate that Div thought

In the process of web development is often encountered a requirement is to click on a div inside do some operations, and click on the page to hide the div elsewhere. For example, a lot of navigation menu, when the menu is expanded, will require to click on the other Non-menu page, hide the menu.

First from the simplest start, if the page has a DIV with ID test, we want to implement the click of the page to hide the div elsewhere:

<div id= "test" style= "Margin:100px;background-color: #3e3; width:100px;height:100px;" >
                        
        </div>

There are generally two ideas for this problem, both of which use the principle of event bubbling, to learn more about the JavaScript event mechanism to see the JavaScript and HTML interaction-Events, this is not the focus of this article, so here is a brief introduction to event bubbling, Event bubbling

Event bubbling of IE: the event is initially received by the most specific element and then propagated up to less specific elements

Netscape event capture: Less specific nodes receive events earlier, while most concrete elements receive events at the end, and event bubbling is the opposite

Dom Event Flow: DOM2 level events Specify that the event flow consists of three phases, the event capture phase, the target phase, the event bubbling phase, the first event capture, the opportunity to intercept the event, then the actual target receives the event, and finally the bubble phrase stage.

Opera, Firefox, Chrome, Safari support DOM event streams, IE does not support event flow, only event bubbling is supported

If you have the following HTML, click the div area and follow the order of the different model event elements in the Click event sequence as shown below:

<! DOCTYPE HTML >

An event object is generated when an event on the DOM is triggered, which contains all information related to the event, including the element that generated the event, the type of event, and so on. All browsers support the event object, but they are supported differently. The event object has a method (W3c:stoppropagation)/property (Ie:cancelbulle=true) to prevent the event from continuing bubbling or capturing. If we want to block bubbles when the event bubbles to an element, we can write a compatible browser method like this:

function Stoppropagation (e) {//The event object is passed into the
            if (e.stoppropagation)//support for the Consortium standard
                E.stoppropagation ();
            else//IE8 and the following browser
                e.cancelbubble = true;
        }

Because all browsers support event bubbling, browser compatibility considerations, we typically bind events using event bubbling rather than event capture. With this in mind, we can look at the following two ways. idea of a

The first kind of thinking is two-step

The first step: Bind the event handler to the document's Click event so that it hides the div

Step two: Bind the event handler on the div click event, prevent the event bubbling, prevent it from bubbling to document, and the OnClick method that invokes document hides the Div.

<script type= "Text/javascript" >
            function stoppropagation (e) {
                if (e.stoppropagation) 
                    E.stoppropagation ();
                else 
                    e.cancelbubble = true;
            }

            $ (document). Bind (' click ', Function () {
                $ (' #test '). CSS (' Display ', ' none ');
            });

            $ (' #test '). Bind (' click ', Function (e) {
                stoppropagation (e);
            });
        </script>

So when you click on the page non-Div area, directly or layer bubbling will invoke the document's OnClick method, hide the Div, and click on the DIV or its child elements, the event will always bubble the div itself, this time to prevent the event continues to bubble, The Doument onclick method is not invoked to cause the div to be hidden, thus fulfilling our requirements. Idea two

As we mentioned earlier, when an event is triggered on the DOM, an event object is created that contains all the information related to the event, including the elements that generate the event, the type of event, and so on. The argument that the div's Click event handler passed in is the event object. There are several different ways to access an event object in IE, depending on the method of the specified event handler. When you add an event handler directly for a DOM element, the event object exists as a property of the Window object.

The event object contains an important attribute: Target (/srcelement), which identifies the original element that triggered the event, and the second idea is to take advantage of this attribute. We can bind the event handler directly to the document's Click event, interpret the event source as a id==test div element or its child element in the event handler, and if it is, the method return does not operate, and if not, hides the div.

<script type= "Text/javascript" >
            $ (document). Bind (' click ', Function (e) {
                var e = e | | window.event;// Browser compatibility
                var elem = E.target | | e.srcelement;
                while (Elem) {//loop to the node, prevent clicking on the div child element
                    if (elem.id && elem.id== ' test ') {return
                        ;
                    }
                    Elem = Elem.parentnode;
                }

                $ (' #test '). CSS (' Display ', ' none '); Clicking is not a div or its child elements
            });
        </script>

So when clicking anywhere on the page will bubble to document Click event, the event handler will determine whether the event source is Id==test div or its child elements, if the method return, otherwise hide the Div, also can achieve our needs. attention points and pros and cons

Both of these ideas depend on event bubbling, so we must be aware of this when dealing with the click events of other related elements, and prevent the event bubbling code from being included in other related elements ' click event handlers.

These two ways are easy to understand, seemingly a better idea of some, it seems that the processing is simpler, do not have to go to the layer to determine the event source, directly to the Click event binding on the Div. This is true in this example, but some complex pages are not the same, if we have a page, there are dozens of div on the page need to click the other place to hide such problems

<div class= "Dialogs" >
        <div class= "dialog" >
            <div id= "1" >1</div>
            <div id= "2" >2</div>
        </div>
        <div class= "dialog" >
            <div id= "1" >1</div>
            < Div id= "2" >2</div>
        </div>
        <div class= "dialog" >
            <div id= "1" >1</div>
            <div id= "2" >2</div>
        </div>
        ...
    </div>

The code we used to write might be like this:

<script type= "Text/javascript" >
            function stoppropagation (e) {
                if (e.stoppropagation) 
                    E.stoppropagation ();
                else 
                    e.cancelbubble = true;
            }

            $ (document). Bind (' click ', Function () {
                $ ('. Dialog '). CSS (' Display ', ' none ');
            });

            $ ('. Dialog '). Bind (' click ', Function (e) {
                stoppropagation (e);
            });
        
        </script>

It looks simple and still, but when we think about it, we find the problem, we have a similar approach on every dialog, and maintaining so many click event handlers is absolutely overhead for memory, causing our pages to run slowly. And if we can dynamically use Ajax to create a new dialog problem again, the newly created dialog cannot implement the hidden functionality. Because the binding function is done and the Click event handler is not bound for the new dialog, we can only do it ourselves. That means that one cannot attach a handler to a DOM element that may not yet exist in the DOM. Because it binds the handler directly to each element, it cannot bind the handler to an element that does not yet exist in the page.

This is the idea of the second show the skill of the time, we look at the two at this time code writing

<script type= ' Text/javascript ' > $ (document). Bind (' click ', Function (e) { var e = e | |
                window.event; var elem = E.target | |
                E.srcelement;
                        while (Elem) {if (Elem.classname && elem.className.indexOf (' dialog ') >-1) { return; 

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.