Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Event capture and bubbling

    // Register bubbling events
    document.querySelector('.div_box').addEventListener('click'.function(e) {
        console.log('%c [target]'.'color: pink; ', e.target);
        console.log('%c [currentTarget]'.'color: pink; ', e.currentTarget);
        console.log('[bubble] div_box is clicked.');
    }, false);

    // Register capture events
    document.querySelector('.div_box').addEventListener('click'.function(e) {
        console.log('%c [target]'.'color: pink; ', e.target);
        console.log('%c [currentTarget]'.'color: pink; ', e.currentTarget);
        console.log('[capture] div_box is clicked.');
    }, true);
Copy the code

Knowledge:

1. (general) events flow in the order of parent capture -> child capture -> child bubble -> parent bubble

The third parameter to addEventListener is of type Boolean, which controls whether the event is executed in the capture or bubble phase. The default value is false, bubble phase;

3. In the callback function, E.target is the element triggered by the event, and E.currenttarget is the binding element of the event

Question 1: How do I prevent events from bubbling?

1. Official method: e.topPropagation ();

2, false block: by judging whether E. target and E. currenttarget ===

Question 2: if both a bubble event and a capture event are bound to an element, which one fires first?

This question depends on the browser version (discuss Chrome)

After Chrome 89.0.4363.0 (included), the standard of event flow is unified. The same DOM element is bound to bubble and capture events, which are executed in the order of capture first and then bubble

Before Chrome 89.0.4363.0 (included), the standard of event flow is unified, the same DOM element, binding bubbling and capturing events, according to the code written order; This means that if the bubbling event code is written first, the bubbling event is executed first and then the capture event is executed before the capture event code is written

The resources

    /** * In older versions of Chrome, 'bubble event is show' followed by 'capture event is show' ** In newer versions of Chrome, the order of 'capture event is show' is followed by 'bubble' ** /
    // Sample code
    document.querySelector('.div_box').addEventListener('click'.function(e) {
        console.log('bubble event is show');
    }, false);

    document.querySelector('.div_box').addEventListener('click'.function(e) {
        console.log('capture event is show');
    }, true);
Copy the code