Event bubble and event capture

cause : Today, I'm encapsulating a bind Function , Find out el.addEventListener The function supports the third parameter ,useCapture: Whether to use event capture , I feel a little fuzzy

  • Js Flow of events

    Which part of the page has a particular event , Example : Draw a set of concentric circles on the paper , If you put your fingers on concentric circles , So it's not a circle , It's all the circles on the paper . On the page, too , If you click a button , Also click the container element of the button , Even click on the whole page

    Flow of events : The order in which the page receives events ,IE and Netscape Two concepts were put forward at the beginning , Two kinds of The event bubbled , Event capture flow

 <!-- If there is such a similar passage html -->
<!DOCTYPE html>
<head><title>bubbling and capture</title></head>
<div id="myDiv">Click me</div>
  • Event Bubbling (event bubbling)

    IE The proposed event handling method , namely At the beginning of the event , Received by the most specific element , Then it propagates up to the unspecific nodes

    If you click... In the example div Elements , So this click The sequence of events spread is as follows :div -> body -> html -> document

    in other words ,click First of all, the event will be div Trigger on element , This element is what we click on , then click Events will follow DOM The trees spread up , It happens at every level of the node , Until it spread to document object

    All browsers support event bubbling , But there will be some differences in the specific implementation , for example IE5.5 And earlier versions of event bubbling will skip Html Elements , Directly from body Jump to the document Elements , and IE9,Firefox,Chrome,Safari Then bubble the event all the way to window object

  • Event capture (event capturing)

    Netscape The net well team has another flow of events called Event capture , The idea of event capture is that less specific nodes should receive events earlier , And the specific node should finally receive the event , The purpose of event capture is to capture an event before it reaches its expected goal , If you still take the above example , single click div

    So the trigger sequence would be like this document -> html -> body -> div

    In the event capture process ,document Object first receives click event , And then events along DOM The trees go down in turn , All the way to the actual goal of time, that is div Elements

    although Netscape It's about developing this flow of events , But now all the newer browsers support this event flow model , Even though “DOM2 Level event ” The specification requires that events should be from document Objects start to spread , But these browsers are all from window Object starts capturing Events

    Because older browsers don't support , So event capture is rarely used , It is recommended to use the event bubbling , Use event capture when there are special needs

  • DOM Flow of events

    "DOM2 Level events " What is? DOM2 Level The specified event flow consists of three phases

    Event capture phase At the target stage Event bubbling stage
    The event is not at the target , Events are delivered from large to small , From the outside down DOM The tree passes , Trigger sequence , From the outside to the inside At the target stage : The event occurs on the target element , And it's part of the bubbling phase of event handling Event bubbling stage : The event starts with the target element , Along DOM The trees pass out , Go to the parent container ,body,html,document Some browsers will arrive at window
  • What is? DOM2 Level ? What is? DOM0 Level ? What is? DOM Event handler level

    event : An action performed by the user or the browser itself , for example click,load,mouseover It's all the names of the events , And the function corresponding to an event , It's called Event handler , The event handler is named after on start , for example click The event handler is onclick,load The way to deal with the incident is onload

    • HTML Event handler

      Some html Element supports some kind of event , You can use a... With the same name as the corresponding time handler html Property to specify , The value of this property is executable javascript Code , for example

      <div onclick="alert(1)"></div>

      This event is triggered by : The bubbling phase triggers

    • DOM0 Level event handler

      html Event handler Of javascript Logic and html Too much coupling

      DOM0 Level event handler

       var btn = document.getElementById('myBtn')
      btn.onclick= function(){

      Here this It points to this trigger element , And through this Object to access any attributes and methods of an element , The event handler added in this way will be in the The bubbling phase is dealt with

      Remove event monitoring btn.onclick = null

    • DOM2 Level event handler

      Two methods :addEventListener and removeEventListener

      be-all DOM The node contains both methods , And take three parameters , Event name to process , Function as an event handler and a Boolean value , Finally, if this Boolean value is true, It means that The capture phase calls the event handler , If it is false It means in The bubble phase calls the event handler

      And the sequence of event flows is Capture - The goal is - Bubbling , The capture phase is before the bubbling event is handled , So instead of true It may affect the normal time sequence

      demo as follows :

       var btn = document.getElementById('myBtn')

      DOM2 The advantage of adding event handlers with the level method is that you can add multiple event handlers , The first two replace the event handler , Because there's only one attribute , And the method of the element will also override

      But it also means , Event handlers cannot be removed by rewriting , So pass removeEventListener To remove the event handler , And anonymous functions cannot be removed

      Most of the time , Both add event handlers to the bubbling phase of the event flow , In this way, all kinds of browsers can be compatible to the maximum extent , It's best to add an event handler to the capture phase only when you need to intercept an event before it reaches the target , If it's not particularly necessary , Registering event handlers in the time capture phase is not recommended

    • IE Event handler

      IE In this way, we can realize the connection with DOM Two similar methods in attachEvent and detachEvent, But only two parameters are accepted , One is the name of the event handler and the event handler function , because IE8 And earlier versions only support event bubbling , So pass attachEvent Any added event handler will be added to Event bubbling stage

      It should be noted that :

      1.attachEvent and DOM The main difference is in the scope of the event handler ,DOM0 Level will be in the scope of the element to which it belongs , and attachEvent The event handler runs in the global scope , So in attachEvent In the added function ,this Point to window

      2.attachEvent When adding multiple events , Not in the order of addition , But in reverse order , Add , Execute first


  • el.addEventListener The third parameter problem of the function is solved , Use this method to represent the binding DOM2 Level event listener , It can be specified repeatedly , The third parameter indicates whether the event is handled in the capture phase , Capture -》 The goal is -》 Bubbling
  • The third parameter defaults to false, If there is no special case, it is not recommended to use the time processing program in the capture phase
  • I understand Flow of events , Capture and bubble ,DOM Event type level (HTML Level event handler ,DOM0 Level event handler ,DOM2 Level event handler ,IE Event handler )
  • Event flow process , First from the outside to the inside , Capture phase , Reach the target stage , Bubbling from the inside out

Javascript More articles on event bubbling and capture in

  1. javascript Events bubbling in 、 Event capture and sequence of event execution

    Talking about JavaScript Of event , Event Bubbling . Event capture . The three topics of preventing default Events , Whether it's an interview or in a normal job , It's hard to avoid . DOM The event standard defines two kinds of event flows , There are significant differences between these two event streams, and they may have an impact on your application ...

  2. javascript Event bubble and event capture in

    1. Event Bubbling IE The event flow of is called event bubbling (event bubbling), That is, the most specific element at the beginning of the event ( The deepest nested node in the document ) receive , And then it propagates to the less specific nodes step by step ( file ). With the following HTML ...

  3. JavaScript Events bubbling in ? The interpretation of the spread of events

    notes : In this paper, the source   Translatable network The bubble of events is that you're learning javaScript A term I come across on the journey , It involves the order in which event processing is called when one element is nested by another , And the two elements register the same event ( for example , Click event ). But there's a risk ...

  4. JavaScript Authoritative design -- Event Bubbling , Capture , Event handle , Event source , Event object ( Brief study notes 18 )

    1. Event bubbling and event capture 2. Events and event handles   3. Event delegation : Using the bubbling technique of events . The event of the child element will eventually bubble to the parent element until it follows the node . Event listeners analyze events bubbling up from child elements . The benefits of event delegation :     1. Each letter ...

  5. JavaScript The event bubbling mechanism in

    Event bubbling mechanism The conditions under which the event bubbled : When the same event handler is set for multiple nested elements , They will trigger event bubbling . In the bubble of events , The innermost element will first trigger its event , Then the next element in the stack triggers the event , And so on , Until we get to the most ...

  6. JavaScript Advanced tutorial 1 JavaScript The flow of events in - Event bubble and event capture

    Let's take a look at the following example code : <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Jav ...

  7. javascript Event mechanism in

    1.javascript In the event . Flow of events javascript The events in are in the form of a stream . An event will also have multiple elements responding at the same time . Sometimes it's not the effect we want , We just need a specific element corresponding to our binding ...

  8. JavaScript Event object in

    JavaScript Event object in JavaScript The event object in is very important , I'm afraid it's the one we use most in the project . It's triggering DOM When you have an event on , An event object is generated event, This object contains all the information related to the event ...

  9. javascript Event delegation in

    I see an interview question these days , Is probably , Let you give it to me 1000 individual li Add a click event , How to add ? Most people's first feeling may be , Every li Add one to the top , In that case , It's estimated that the interview will be GG 了 , Here is the ...

  10. understand javascript In the event ( Two )

    The contents of this article are as follows : zero . Greetings One . Classification of events Two . Event agent 2.1 Question elicitation 2.2 What is an event agent 2.3 Complete example Two . Event agent 3、 ... and . The use of the idea of event proxy Four . summary zero . Greetings This blog should have appeared in two months to ...

Random recommendation

  1. JVM To configure

    1. Heap settings JVM There are three limits to the maximum heap size in : Operating system bits (32-bt still 64-bit) Limit : Available virtual memory limit : The available physical memory limit of the system . java -Xmx3550m -Xms3550m -Xmn2g  ...

  2. Cross-Origin Resource Sharing Protocol is introduced

    Conventional Ajax The request can only obtain resources under the same domain name , however HTML5 Breaking the limit , allow Ajax Initiate cross domain requests . Browsers can initiate cross domain requests , For example, you can chain a picture or script of an Outland . however Javascript foot ...

  3. 【mysql】 Statistical database 、 Watch size

    1. View the size of all databases under the database instance , The result is that MB In units of mysql> select table_schema,sum(data_length)/1024/1024 as data_leng ...

  4. How to use it SQL SERVER Hybrid Authentication

    Reprint :http://jingyan.baidu.com/article/380abd0aa8f2311d90192cd0.html Everybody knows sql server There are two ways of login verification , namely sql ser ...

  5. C Programming language exercises 1-8

    practice 1-8 Write a statistical space . Tab and newline number of procedures . The code is as follows : #include <stdio.h> // Contains information about the standard library . int main() // Definition is named main Function of , it ...

  6. C# operation Excel Collect and sort out frequently asked questions

    C# operation Excel Collect and sort out frequently asked questions ( Regular updates , Welcome to exchange ) There are often items that need to be exported as Excel file , Or import a Excel To operate , So how to be in C# In the operation Excel The document became a ...

  7. unity establish NGUI typeface

    1.NGUI -> Open -> Font Maker open FoontMaker window . 2. spot Source choice .ttf typeface , It has to be in Chinese , Otherwise it will go wrong . 3. spot Custom Radio button , Input ...

  8. Asp.Net Core----- Introduction and installation

    Asp.Net Core brief introduction ASP.NET Core It's a new open source . Cross platform framework , It can be used to build modern Cloud Applications Based on network connectivity , such as :Web application ,IoT(Internet Of Things, Object association ...

  9. Python Basics ----- Process control

    ------   conditional if Conditional judgment grammar : Pay attention to : 1. from if Conditions start 2. Add a space after the keyword 3. Conditions are followed by : 4. accord with python Code indent format 5. There are many combinations of conditional judgment ...

  10. [py]python Of time and datetime What day of the week does the module get

    import time import datetime # What day is today today=int(time.strftime("%w")) print today # What day of the week is a date any ...