JS event bubbling and event capture

Source: Internet
Author: User
Tags event listener

First, event bubbling

Event bubbling is the process of starting from the target node in the event, and then querying the first layer of the parent node in turn until the document and executing the same event.

  Btn1.addeventlistener (' click ', function  Span style= "COLOR: #000000" > (e) { // true for the Thing Piece capture, False for event bubbling  // false is the default, bubbling mode execution  //  Click Btn1, if event bubbling, first execute the Click event on BTN1, Then executes the Click event on the parent element div1  //  If event capture, Executes the Click event on the parent element first, and then executes the Click event on btn1  var  e= e| |        window.event;    Alert ( ' You clicked Btn1 '  false ); 
Div1.addeventlistener (' click ', Function (e) {

Alert (' You clicked Div1 ');
},false);

This way of writing, when you click Btn1, the first pop-up "you clicked Btn1", and then popped "you clicked Div1";

Second, event capture

Event capture is the process of executing the same event from document, starting with a layer to find the target node, and then executing the same event.

Btn1.addeventlistener (' click ',function(e) {//true for event capture, false for event bubbling        //false is the default, bubbling mode is performed        //When you click Btn1, the Click event on the BTN1 is executed first, and then the Click event on the parent element is performed if the event is bubbling .        //if it is an event capture, the Click event on the parent element is executed first, and then the click event on the BTN1 is executed        varE= e| |window.event; Alert (' You clicked on the Btn1 '); },true); Div1.addeventlistener (' Click ',function(e) {alert (' You clicked on the Div1 '); },true);

This way of writing, when you click Btn1, the first pop-up "you clicked Div1", and then popped "you clicked Btn1";

Third, block event bubbling and event capture

IE differs from other browsers in blocking event bubbling and capturing methods;

The first is the difference of the event;

The event object represents the state of the incident, such as the element in which the event occurred, the state of the keyboard key, the position of the mouse, and the state of the mouse button.

Events are often used in conjunction with functions, and functions are not executed until the event occurs!

The event output in IE is event;event in IE as a global function and can be called anywhere.

The event is output in FF, which can only be invoked in practice in FF, and the event is passed into the function as a parameter.

The other browsers are both possible;

Therefore, browser compatibility is required when determining event

var e = event| | window.event;

Equivalent to E = e?event:window.event;

In this way, IE identifies the event, and other browsers identify the window.event;

There are also different ways to block events

Ie:e.cancelbubble = true; Prevent event distribution by setting E.cancelbubble to true;

Standard browser: e.stoppropagation (); The Stoppropagation method of the standard browser can be set to no longer distribute events.

The compatible code is as follows:

var e = event| | window.event;         if (e.stoppropagation) {            e.stoppropagation (); // Standard browser        } Else {            true;   IE browser        }
Iv. Event delegation method relies on event bubbling mechanism

Traditional event Bindings

We give each Li to the event that the background color turns red after a fixed point hit;

var uli = document.getElementById (' uli ');     var lis = uli.getelementsbytagname (' li ');      for (var i = 0;i<lis.length;i++) {        function() {           this. Style.backgroundcolor = ' red ';        }    }     // This allows us to add mouse events on top of Li.     // But if we could have a lot of Li with a for loop, that would affect performance. 

An instance of an event delegate

HTML unchanged, changing only the method of event binding

  var  uli = document.getElementById (' Uli ')    Span style= "color: #000000"); Uli.addeventlistener ( ' click ', function   ( Event) { var  e = event| |        window.event;  var  target = e.target| | E.srcelement; //  // e.target is a standard browser method  // e.srcelement is a method in IE  if  (target.nodeName.toUpperCase () = = ' LI ' = ' Red ' ; }    });

The standard browser queries the event node by: window. Event.target;

IE browser Query the event node method is:event.srcelement;

This can be done when you click on Li to bubble up to UL, and then perform the binding event on UL, so that you do not have to bind each li a click event.

and the newly added LI element can also bind such events without rebinding

You can use Removeelementlistener to unbind an event function

V. Binding event listening methods traditional binding events

On + click, mouseover, KeyUp, etc.

of traditional bindings

Advantages

    • Very simple and stable to make sure it works the same in the different browsers you use
    • This keyword refers to the current element when handling an event, which is helpful

Disadvantages

Multiple functions that bind the same event are overwritten and only the last one is triggered.

Uli.onclick = function () {

Alert (' 1 ');

}

Uli.onclick = function () {

Alert (' 2 ');

}

The execution of such a notation can only be performed with alert (' 2 '); Unbind with uli.onclick = null;

Binding Event

Uli.addeventlistener (' click ', function () {...},false);

    1. Benefits of Binding
      • This method supports both the capture and bubbling phases of event processing. The event stage depends on the last parameter setting of AddEventListener: false (bubbling) or true (capture).
      • Inside the event handler function, the This keyword refers to the current element.
      • Event objects can always be captured by processing the first parameter (e) of the function.
      • You can bind as many events as you want for the same element without overwriting previously bound events
    2. Disadvantages of the binding of the Consortium
      • IE does not support, you must use IE's attachevent function instead.

Unbind with RemoveEventListener (' click ', Fucntion () {...});

IE Binding Event

IE binds events with the Attachevent method

function (){        // ...    });
    1. Advantages of IE mode
      • You can bind as many events as you want for the same element, and not overwrite previously bound events.
    2. Disadvantages of IE mode
      • IE only supports the bubbling phase of event capture
      • The This keyword within the event listener function points to the Window object, not the current element (a huge disadvantage of IE)
      • The event object exists only with the window.event parameter
      • The event must be named in the form of ontype, for example, onclick rather than click
      • Only IE is available. You must use the Addeventlistene in a non-IE browser

Unbind function with DetachEvent (' onclick ', Fucntion () {})

JS event bubbling and event capture

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.