Ask a few questions first. Can you flash the answers quickly?

  1. What about bottom-up (bubbling) events and top-down (capturing) events?
  2. Capture and bubble exist together, which is effective?
  3. Does jquery’s ON or bind bubble or capture?
  4. Can bubbling be stopped? Can capture be stopped?
  5. The difference between stopPropagation and stopImmediatePropagation
  6. The Event bubbles, Event. EventPhase
  7. Event. Cancelable, Event. CancelBubble, Event. Defaultspoiled
  8. The commonly used skill

Capture and bubble diagram of JS events

Here’s an example:

What will s1 print when I click s2?

<div id="s1">s1 <div id="s2">s2</div> </div> <script> s1.adDeventListener ("click",function(e){console.log("s1 bubble "); },false); AddEventListener ("click",function(e){console.log("s2 bubble event "); },false); S1. addEventListener("click",function(e){console.log("s1 catch event "); },true); S2. addEventListener("click",function(e){console.log("s2 catches events "); },true); </script> //s1 captures events // S2 bubbles events //s2 captures events // S1 bubbles eventsCopy the code

S2 -> document-> HTML ->body->s1->s2

Bubbles and capture events are registered on S2. If bubbles are registered first and capture is registered later, bubbles will be executed first and “S2 bubble event” will be output.

Execute the registered event on S2, capture event, output “S2 capture event”

Now let’s go to the bubble stage. Follow s2-> S1 ->body-> HTML -> Documen to find a bubble event on S1 and print “S1 bubble Event”.

JQuery’s on event is bubbling

The source code for jquery’s ON event is posted below

The commonly used skill

Onclick –> event bubbling, overwriting onlick overwrites previous properties, no compatibility issues

ele.onclik = null;   // Unbind the click event and set the onlick property to null

Copy the code

Block default events (href=”” link, submit form submission, etc.)

  1. return false; The default event that prevents events bound by an exclusive property (via on)

    ele.onclick = function() {...// Your code
        return false;              // Prevent default event behavior by returning false
    }
    Copy the code
    However, in jQuery, we often use return False to prevent the default behavior of browsers, so what does “return False” actually do?

    Every time you call “return false”, it actually does three things:

    • event.preventDefault();

    • event.stopPropagation();

    • Stop the callback function and return immediately.

    PreventDefault is the only thing preventing the browser from performing the default behavior, unless you want to stop event bubbling, using return False will put a big bug in your code.

    The source code of jQuery is attached below



  2. event.preventDefault( ); The default event that blocks the event added via addEventListener()

    Element. The addEventListener (" click ",function(e){
        var event = e || window.event; ... event.preventDefault( );// Block the default event
    },false);
    
    Copy the code
  3. event.returnValue = false; Default event to block events added via attachEvent() (this event is specific to Internet Explorer)

    Element. AttachEvent (" onclick ",function(e){
        var event = e || window.event; ... event.returnValue =false;  // Block the default event
    },false);
    
    Copy the code

Encapsulate event binding and event unbinding as a function, compatible with browsers including IE6 and above (although it is now mostly abandoned below IE9 HHHH)

// Event binding
function addEvent(element, eType, handle, bol) {
    if(element.addEventListener){           // If addEventListener is supported
        element.addEventListener(eType, handle, bol);
    }else if(element.attachEvent){          // If attachEvent is supported
        element.attachEvent("on"+eType, handle);
    }else{                                  // Otherwise use the compatible onclick binding
        element["on"+eType] = handle; }}// Unbind events
function removeEvent(element, eType, handle, bol) {
    if(element.addEventListener){
        element.removeEventListener(eType, handle, bol);
    }else if(element.attachEvent){
        element.detachEvent("on"+eType, handle);
    }else{
        element["on"+eType] = null; }}Copy the code

Events stop propagating stopPropagation and stopImmediatePropagation

// Events propagate to the Element and are no longer propagated downwards
element.addEventListener('click'.function (event) {
  event.stopPropagation();
}, true);

// Events bubble up to the element and no longer bubble up
element.addEventListener('click'.function (event) {
  event.stopPropagation();
}, false);

Copy the code

However, the stopPropagation method only blocks propagation of the element’s current event (bubble or capture) and does not block the listener for other click events on this node. That is, rather than completely canceling the Click event, it can create a new click event as normal.

element.addEventListener('click'.function (event) {
  event.stopPropagation();
  console.log(1);
});

element.addEventListener('click'.function(event) {
  / / triggers
  console.log(2);
});
Copy the code

If you want to stop the propagation of this event completely and not fire all subsequent click listeners, you can use the stopImmediatePropagation method. Note: for this event, if you write the method in click, the binding method on the element will be invalid, but other mousedown, mouseover methods, etc., will still work. Kiss ~ has been measured

element.addEventListener('click'.function (event) {
  / / triggers
  console.log(' change method within executable '); event.stopImmediatePropagation();/ / triggers
  console.log(1);
});

element.addEventListener('click'.function(event) {
  // Will not be triggered
  console.log(2);
});

/ / Jquery in the same way
$(element).click(function() {
  // Will not trigger
  console.log (' jquery click ')}) $(element). Hoverfunction() {
  / / triggers
  console.log (' jquery click ')})Copy the code

The Event bubbles, Event. EventPhase

The event. bubbles property returns a Boolean value indicating whether the current Event will bubble. This property is read-only and is generally used to see if the Event instance can bubble. As mentioned earlier, events generated by the Event constructor do not bubble by default unless explicitly stated. The following code can be used to determine whether the event is bubbling to execute different functions.

function goInput(e) {
  if(! e.bubbles) { passItOn(e); }else{ doOutput(e); }}Copy the code

We specifically checked the events that do not support bubbling:

  • UI events (Load, Unload, Scroll, resize)
  • Blur, focus
  • Mouse events (mouseleave, mouseenter)

The event.EventPhase property returns an integer constant representing the current phase of the Event. This property is read-only.

var phase = event.eventPhase;
Copy the code

The return value of event.EventPhase has four possibilities.

  • 0, the event is not currently occurring.
  • 1. The event is currently in the capture phase, that is, in the propagation process from the ancestor node to the target node.
  • 2. The Event reaches the target node that the Event. Target attribute points to.
  • 3. The event is in the bubbling phase, that is, in the process of backward propagation from the target node to the ancestor node.

Event. Cancelable, Event. CancelBubble, Event. Defaultspoiled

The event. cancelable property returns a Boolean value indicating whether the Event can be cancelled. This property is read-only and is generally used to understand the characteristics of the Event instance.

Most browsers’ native events can be cancelled. For example, if you cancel the click event, clicking on the link will not work. But events generated by the Event constructor cannot be cancelled by default unless explicitly declared.

var evt = new Event('foo');
evt.cancelable  // false
Copy the code

If the event.cancelable property is true, call event.preventDefault () to cancel the Event and prevent the browser’s default behavior on the Event. Note that this method simply cancels the default effect of the event on the current element and does not prevent the event from propagating. If propagation is to be stopped, the stopPropagation() or stopImmediatePropagation() methods can be used.

function preventEvent(event) {
  if (event.cancelable) {
    event.preventDefault();
  } else {
    console.warn('This event couldn\'t be canceled.');
    console.dir(event); }}Copy the code

The Event.cancelBubble property is a Boolean value that can be set by itself. If set to true, event.stopPropagation () is executed to prevent propagation of events.

Note: MDN states that this feature has been removed from the Web standards. although some browsers still support it, it may be discontinued at some point in the future. please try not to use this feature. Use the event.stopPropagation() method instead of this nonstandard attribute. Cancelbubb-mdn

The event. defaultSpoiled property returns a Boolean indicating whether the Event. PreventDefault method was called for the Event. This property is read-only.

if (event.defaultPrevented) {
  console.log('The event has been canceled.');
}
Copy the code

Main Reference Documents:

Detail the event mechanism in JS (with examples)

The event model