1. Event flow

  • Event receiving order. IE supports event bubbler streams, and Nestcape Communicator supports event capture streams

1. Events bubble up

  • Events bubble up because events are defined to fire from the most specific element (the deepest node in the document tree) and propagate up to less specific elements.
  • Modern browsers all support event bubbling. Bubble all the way to the Window object

2. Event capture

  • Event capture means that the least specific node receives the event first, and the most specific node receives the event last.
  • Event capture is designed to intercept an event before it reaches its final destination.

3. DOM event flow

  • There are three phases: event capture, destination, and event bubbling

    ! [image-20210622001701564](/Users/hanyefeng/Library/Application Support/typora-user-images/image-20210622001701564.png)

  • DOM event flow, the actual target does not receive events during the capture phase. It is triggered when the target stage is reached and is usually considered part of the bubbling stage

  • There are two opportunities to process events on the event target.

2. Event handlers

  • The function called in response to an event is called an event handler (event listener).

1. HTML event handlers

<input type="button" value="click me" onclick="xxx">

  • The event handler can access everything in the global scope.
  • An event handler specified as a property creates a function that encapsulates the value of the property, a local variableevent
  • This corresponds to the target element of the event
  • Both document and element members can be accessed as local variables (with)
  • In a form, you can directly access other members of the same form
  • Question:
    • Timing issues. Interaction may have occurred, but the event handler code is not yet executable.
    • Extensions to the event handler scope chain can lead to different results in different browsers.
    • HTML is strongly coupled to JavaScript, and if you need to change the event handler, you have to change the code in two places.

DOM0 event handler

  • Assign a function to an event handler property.

    let btn = document.getElementById("myBtn")
    btn.onclick = function() {
      console.log("Clicked")}Copy the code
  • This is equal to the element itself

  • Remove event handler btn.onclick = null

DOM2 event handler

  • addEventListener()andremoveEventListener()
  • Parameters: event name, event handler, whether to capture (Boolean) Default false
let btn = document.getElementById("myBtn")
btn.addEventListener("click".() = > {
	console.log(this.id)
}, false)
Copy the code
  • The advantage is that you can add multiple event handlers in order to fire.
  • throughremoveEventListener()To pass in the same arguments as to add to remove, so anonymous functions cannot remove.

4, IE event handler

  • attachEvent()anddetachEvent()
  • Parameters: The name of the event handler and the event handler. Only bubbles are supported
var btn = document.getElementById("myBtn")
btn.attachEvent("onclick".function(){
  console.log("Clicked")})Copy the code
  • This is equal to the window
  • Multiple event handlers can be added, but the order in which they are triggered is reversed
  • throughdetachEvent()Remove, you need to pass in the same parameters as add to remove

Cross browser event handlers

  • addHandler()

  • removeHandler()

var EventUtil = {
  addHandler: function(element, type, handler) {
    if(element.addEvenetListener) {
      element.addEventListener(type, handler, false)}else if(element.attachEvent) {
      element.attachEvent("on" + type, handler)
    }else {
      element["on" + type] = handler
    }
  },
  removeHandler: function(element, type, handler) {
    if(element.removeEvenetListener) {
      element.removeEventListener(type, handler, false)}else if(element.detachEvent) {
      element.detachEvent("on" + type, handler)
    }else {
      element["on" + type] = null}}}Copy the code

3. Event objects

  • When an event occurs in the DOM, all relevant information is stored in the Event object.
  • Contains basic information such as the element that caused the event, the type of event that occurred, and any other data that might be relevant to a particular event.

DOM event objects

  • All event objects contain the following common properties and methods
Properties/methods type Read/write instructions
bubbles Boolean value read-only Indicates whether the event bubbles
cancelable Boolean value read-only Indicates whether the default behavior of an event can be undone
currentTarget The element read-only The element of the current event handler
defaultPrevented Boolean value read-only True indicates that the preventDefault() method has been called
detail The integer read-only Additional information about the event
eventPhase The integer read-only Event handler phase: 1 represents the capture phase,

2 represents reaching the target and 3 represents the bubbling phase
preventDefault() function read-only Cancel event default behavior (cancelable is true)
stopImmediatePropagation() function read-only Cancel all subsequent event capture or event bubbling,

And prevents any subsequent event handlers from being called
stopPropagation() function read-only Cancel all subsequent event capture or event bubbling (bubbles is true available)
target The element read-only Event goals
trusted (isTrusted) Boolean value read-only True indicates that the event was generated by the browser, false indicates that it was created by the developer
type string read-only The type of event that is triggered
View AbstractView read-only The abstract view associated with the event, equal to the window object where the event occurred
  • The event object exists only for the duration of the event handler’s execution and is destroyed once the execution is complete.

2. IE event object

  • Event is a property of the window
Properties/methods type Read/write instructions
cancelBubble Boolean value Read/write Default is false, set to true to debubble
returnValue Boolean value Read/write Default true, set to false to cancel the event default behavior
srcElement The element read-only Time target
type string read-only The type of event that triggers

3. Cross-browser event objects

var EventUtil = {
  addHandler: function(element, type, handler) {
  / /...
 },
  getEvent: function(event) {
    return event ? event : window.event
  },
  getTarget: function(event) {
    return event.target || event.srcElement
  },
  preventDefault: function(event) {
    if(event.preventDefault) {
      event.preventDefault()
    }else {
      event.returnValue = false}},removeHandler: function(element, type, handler) {
    / /...
  },
  stopPropagation: function(event) {
    if(event.stopPropagation) {
      event.stopPropagation()
    }else {
      event.cancelBubble = true}}}Copy the code

4. Event type

1. User interface Events (UIEvent)

  • Involves generic browser events that interact with a BOM

  • Load: window when the page is loaded, when all panes are loaded in the window cover, when the image is loaded in the < IMG > element, and when the corresponding object is loaded in the element

  • Unload: window After a page has been completely unloaded, fires on a window sleeve after all panes have been unloaded, or on a element after the corresponding object has been unloaded

  • Abort: Triggered when the user prematurely aborts the download of the corresponding object on the element before it has finished loading

  • Error: Raised when a JavaScript error occurs on a window, when the specified image cannot be loaded on an element, when the corresponding object cannot be loaded on an element, and when one or more panes cannot complete loading on a window cover

  • Select: Triggered in a text box ( or textarea) when the user selects one or more characters

  • Resize: Triggered when a window or pane is scaled.

  • Scroll: Triggered on an element that contains a scrollbar when the user scrolls it

1. Load events

  • The load event is triggered when the entire page (including all external resources such as images, JavaScript files, and CSS files) is loaded
window.addEventListener("load".(event) = > {
  console.log("Loaded!")})Copy the code
<! DOCTYPEhtml>
<html>
<head>
  <title>Load Event Example</title>
</head>
<body onload="console.log('Loaded! ')">
</body>
</html>
Copy the code
  • Load events are also triggered on images, both in the DOM and non-DOM. You can give it directly in HTML<img>The onload attribute of the element specifies the event handler
< img src="smile.gif" onload="console.log('Image loaded.')">
Copy the code
let image = document.getElementById("myImage")
image.addEventListener("load".(event) = > {
  console.log(event.target.src)
})
Copy the code
  • <script>The element fires the Load event after the JavaScript file is loaded

2. Unload Events

  • Navigation from one page to another is often used to clean up references and avoid memory leaks.
window.addEventListener("unload".(event) = > {
  console.log("Unloaded!")})Copy the code

3. Resize event

  • Triggered when the browser window is scaled to a new height or width.
  • Maximization minimization also triggers
window.addEventListener("resize".(event) = > {
  console.log("Resized!")})Copy the code

4. Scroll event

window.addEventListener("scroll".(event) = > {
  if(document.compatMode === "CSS1Compat") {
    console.log(document.documentElement.scrollTop)
  }else {
    console.log(document.body.scrollTop)
  }
})
Copy the code

2. FocusEvent

  • Triggered when an element gains and loses focus

  • Blur: Triggered when an element loses focus, does not bubble

  • Focus: Triggers when the element gains focus, without bubbling

  • Focusin: Fires when the element gains focus. It’s a bubbling version of the Focus

  • Focusout: Fires when an element loses focus. It’s a generic version of Blur

  • When the focus moves from one element to another on the page

    1. Focusout fires on elements that have lost focus
    2. Focusin fires on the element that gets focus
    3. Blur triggers on elements that are out of focus
    4. Focus fires on the element that gets the focus

3. Mouseevents & WheelEvents

  • Mouse events
    • click: Triggered when the user clicks the left mouse button
    • dblclick: Triggered when the user double-clicks the left mouse button
    • mousedown: Triggered when the user presses any mouse key
    • mouseenterTriggered when the user moves the mouse cursor from outside the element to inside it. Does not bubble and does not trigger over descendant elements.
    • mouseleave: Triggered when the user moves the mouse cursor from inside an element to outside it. Does not bubble and does not trigger over descendant elements.
    • mousemove: Fires repeatedly as the mouse cursor moves over the element
    • mouseout: Triggered when the user moves the cursor from one element to another, which can be an external element or a child element of the original element.
    • mouseover: Triggered when the user moves the mouse cursor from outside to inside an element.
    • mouseup: Triggered when the user releases the mouse key
  • Wheel events
    • mousewheel: Scroll wheel interaction on a mouse wheel or similar device with a scroll wheel

1. Client coordinates

  • Mouse cursor client browser viewport coordinates, saved in the EventclientXandclientYOn.

2. Page coordinates

  • The coordinates of the mouse cursor on the page when the mouse occurs are saved in the eventpageXandpageYOn.
  • No page scrolls with the same coordinates as the client

Screen coordinates

  • The coordinates of the mouse cursor on the screen when the mouse occurs are saved in the eventscreenXandscreenYOn.

4. Modifiers

  • Shift, Ctrl, Alt, Meta
  • ShiftKey, CtrlKey, AltKey, MetaKey. The value is true when pressed, false otherwise

5. Related elements

  • relatedTargetRepresents related element (as opposed to target element) information (mouseover, mouseout only)
var EventUtil = {
  getRelatedTarget: function(event) {
    if(event.relatedTarget) {
      return event.relatedTarget
    }else if(event.toElement) {
      return event.toElement
    }else if(event.fromElement) {
      return event.fromElement
    }
  }
}
Copy the code

6, mouse button

  • The button properties
    • 0 a primary key
    • 1 roller
    • 2 pair of keys

7. Additional event information

  • detailThe: mouse event represents how many clicks occurred in a given pixel position, reset to 0 if moved between mouseDown and Mouseup

The Mousewheel event

  • Mouse wheel scroll events
  • wheelDeltaProperty, mouse forward scroll +120, backward scroll -120

9. Touch screen devices

  • Dblclick events are not supported
  • A single finger click can start the Mousemove event
  • Mousemove also triggers museover and Mouseout events
  • Double pointing and sliding triggers mouseWheel and Scroll events

10. Accessibility

4, Keyboard and input events (KeyboardEvent & InputEvent)

  • keydown, triggered when the user presses a key on the keyboard, hold down repeatedly triggered.
  • keypress, triggered when the user presses a key on the keyboard and produces a character. Esc also fires. DOM3 Events deprecates this event and is recommendedtextInputThe event
  • keyupWhen the user releases a key on the keyboard
  • textInput, an input event that makes it easier to intercept text input before it is displayed to the user, and is triggered before the text is inserted into the text box.
  • Supports the same modifier keys as mouse events

1, the key code

  • Keydown and KeyUp events, of the event objectkeyCodeProperty stores a key code corresponding to a specific key on the keyboard. For letters and numbers, keyCode is consistent with the ASCII encoding of lowercase letters and numbers.

2. Character encoding

  • The charCode property, the keypress event, is set and contains the corresponding ASCII code, usually 0.

    var EventUtil = {
      getCharCode: function(event) {
        if(typeof event.charCode == 'number') {
          return event.charCode
        }else {
          return event.keyCode
        }
      }
    }
    Copy the code
  • This can be converted to an actual String by string.fromCharcode ()

3. Changes of DOM3

  • Defines thekeyandcharProperty, undefinedcharCode
  • keyInstead ofkeyCodeAnd contains a string. Equals the text character when the character key is pressed. When a non-character key is pressed, the key value is the key name.
  • charIn the character key withkeySimilar, but null for non-character keys
  • Not recommendedkey,char
  • location, the value indicates where the key is pressed, 0 default, 1 left, 2 right, 3 numeric keypad, 4 mobile device (virtual keyboard), 5 gamepad
  • getModifierState()Accepts an argument, a string equal to Shift, Control, Alt, AliGraph, Meta, representing the modifier key to be examined. Returns true if active

The textInput event

  • Trigger only in editable areas
  • Triggered only when a new character is inserted.
  • dataProperty that contains the character to be inserted. The data value is always the value to be inserted.
  • inputMethodProperty representing the input means
    • 0 uncertain
    • 1 the keyboard
    • 2 paste
    • 3 drag and drop
    • 4 IME
    • 5 the form
    • 6 handwritten
    • 7 voice
    • 8 combination
    • 9 the script

5. Keyboard events on the device

5. Composite events

  • compositionstartTriggered when the IME’s text composition system is turned on, indicating that input is about to begin
    • Data contains the text being edited
  • compositionupdateTriggered when a new character is inserted into an input field
    • Data contains the new character to be inserted
  • compositionendTriggered when the IME’s text synthesis system shuts down to resume normal keyboard input.
    • Data contains everything entered during this composition

6. Change events

  • Provide notification when DOM changes

7. HTML5 events

Contextmenu event

  • The right mouse button action event is specifically used to indicate when the context menu should be displayed, allowing developers to cancel the default context menu and provide custom menus.
  • contentmenuEvent bubbling, just specify an event handler for document.
  • The target is the element that triggers the action, use event.preventDefault() to cancel the default

2. Beforeunload events

  • Triggered on Windows, giving developers the opportunity to prevent the page from being unmounted. The page cannot be cancelled.
  • You need to set event.returnValue to the string that the window will display and return as the function value.

3, DOMContentLoaded event

  • Trigger immediately after the DOM tree is built, without waiting for images, JavaScript files, CSS files, or other resources to load.
  • The event actually targets Document, but bubbles to Window
  • The event contains nothing, except that target is a Document.
  • Often used to add event handlers or perform other DOM operations, always firing before load.
  • For browsers that do not support this event, use the setTimeout function with a timeout of 0

4. Readystatechange event

  • supportreadystatechangeOne for each object of the eventreadyStateProperty, the possible values are as follows
    • uninitialized: The object exists and has not been initialized
    • loading: Object is loading data
    • loaded: The object has finished loading data
    • interactive: Objects can interact, but are not yet loaded
    • complete: The object is loaded
  • Order and quantity are not guaranteed.

Pageshow event and PageHide event

  • Round-trip caching is designed to speed up page switching when using the browser’s forward and back buttons.

  • Keep the entire page in memory, and navigation to the page does not trigger a Load event

  • Pageshow, which fires when the page is displayed, whether or not it comes from the round-trip cache.

    • On a newly loaded page, pagesHow fires after the load event
    • On pages from the round-trip cache, pagesHow fires after the page has fully recovered
    • The event target is Document, but the event handler must be added to the Window
    • persistedThe additional attribute of event is a Boolean value indicating whether the page is stored in the round-trip cache.
  • Pagehide, fired after the page is unloaded from the browser and before the Unload event.

    • persistedThe additional attribute of event is a Boolean value indicating whether the page will be saved in the round-trip cache.
  • Pages registered with an Unload event are automatically excluded from the round-trip cache.

6. Hashchange event

  • Used to notify developers when the URL hash table changes.
  • New property of the Event objectoldURLandnewURLSave the urls before and after the change

8. Device events

  • Device events can be used to determine how the user is using the device.

1. Orientationchange event

  • Used to determine whether the user’s device is in vertical or horizontal mode.
  • Moving Safari exposes the Window. orientation property on Windows.
    • 0 Vertical mode
    • 90 Left turn horizontal mode
    • -90 Turn right to horizontal mode
  • Whenever the user spins the device to change mode, the OrientationChange event is triggered

Deviceorientation Events

  • To obtain the accelerometer information of the equipment, only reflect the orientation of the equipment in the air, and do not involve the moving-related information.

3. Devicemotion Event

  • Used to indicate that the device is actually moving, not just changing orientation.

9. Touch and gesture events

1. Touch events

  • touchstart: Finger on the screen trigger (one finger is already on the screen)
  • touchmove: Continuous trigger as your finger slides across the screen. callpreventDefault()It stops scrolling.
  • touchend: Triggered when the finger is removed from the screen
  • touchcancel: Triggered when the system stops tracking touch.
    • They all bubble up, they can all be cancelled
    • Event contains the common properties of mouse events
      • Bubbles, Cancelable, View, clientX, clientY, screenX, screenY, detail, altKey, shiftKey, ctrlKey and metaKey
    • The following three properties track contacts
      • touches: An array of Touch objects representing each Touch on the current screen
      • targetTouches: An array of Touch objects representing contacts specific to the event target
      • changedTouches: An array of Touch objects representing the Touch points that have changed since the last user action
    • Properties that each Touch object contains
      • clientX: X coordinate of the contact on the viewport
      • clientY: Y coordinate of the contact on the viewport
      • identifier: contact ID
      • pageX: The x coordinate of the contact on the page
      • pageY: Y coordinate of the contact on the page
      • screenX: The touch point is in the screen x coordinate
      • screenY: The y coordinate of the contact on the screen
      • target: Touches the event target of the event

2. Gesture events

  • Triggered when two fingers touch the screen and the relative distance or rotation Angle changes.
  • gesturestart: Trigger when one finger is already on the screen by placing another finger on the screen
  • gestureschange: Triggered when any finger changes position on the screen.
  • gestureend: Triggers when one of the fingers leaves the screen.
  • The event contains basic public properties
  • Event Additional propertiesrotationandscale
    • rotationIndicates the degree of finger rotation, negative value indicates counterclockwise rotation, positive value indicates clockwise rotation.
    • scaleIndicates the degree of change in the distance between the fingers.

10. Event Reference

5. Memory and performance

1. Event delegation

  • Too many event handler solutions use event delegates. With event bubbling, you can use just one event handler to manage one type of event.
  • Advantages:
    • The Document object is always available, and you can add event handlers to it at any time.
    • Save time spent setting up a page event handler by specifying only one event handler to save references to the DOM.
    • Reduce the memory required for the entire page and improve overall performance.

2. Delete event handlers

  • Remove unnecessary event handlers in time to improve performance
  • Cause of the problem
    • Delete an element with an event handler. If the deleted element has an event handler on it, it will not be cleaned up properly by the garbage collector.
      • You need to manually remove its event handler before deleting it.
    • The event handler is not cleaned up after the page unloads and remains in memory.
      • In the OnUnload event handler, remove all event handlers before the page is unloaded. Deleted pages are not saved in the round-trip cache.

6. Simulated events

1. DOM event simulation

  • document.createEvent()Create an Event object. Receives a string representing the event type to be created. Available value:
    • UIEventsUIEvent User interface events
    • MouseEventsMouseEvent Generic mouse events
    • HTMLEventsNo generic HTML event
  • dispatchEvent()Triggering event
    • This method exists on all DOM nodes that support events
    • The argument is the event object to fire the event

1. Simulate mouse events

  • Create a MouseEvent object and pass in “MouseEvent”

  • There is the initMouseEvent() method, which specifies mouse-specific information for the new object.

    • Type The type of event to fire, such as click

    • Whether the bubbles bubble

    • Cancelable: indicates whether the event can be cancelled.

    • View: The view associated with the event. It’s basically always document.DefaultView.

    • Detail: additional information about the event. Used only by event handlers, usually 0.

    • ScreenX (integer) : The x coordinate of the event relative to the screen.

    • ScreenY (integer) : The y coordinate of the event relative to the screen.

    • ClientX (integer) : The x-coordinate of the event relative to the viewport.

    • ClientY (integer) : The y-coordinate of the event relative to the viewport.

    • Ctrlkey (Boolean) : Indicates whether Ctrl key is pressed. The default is false.

    • Altkey (Boolean) : Indicates whether the Alt key was pressed. The default is false

    • Shiftkey (Boolean) : Indicates whether the Shift key is pressed. The default is false.

    • Metakey (Boolean) : indicates whether the Meta key is pressed. The default is false.

    • Button (integer) : Indicates which button is pressed. The default is 0.

    • RelatedTarget: The object associated with the event. Only used when simulating mouseover and Mouseout

2. Simulate keyboard events

  • Create a KeyboardEvent object and pass in “KeyboardEvent”

  • There is an initKeyboardEvent() method that receives arguments

    • Type: Indicates the type of event to be triggered, such as keyDown

    • Bubbles: Whether there are bubbles

    • Cancelable: indicates whether the event can be cancelled.

    • View: The view associated with the event. It’s basically always document.DefaultView.

    • Key: string code for pressing a key

    • Location: keyboard location

    • A list of space-separated modifiers, such as “Shift”

    • Repeat: How many times do you press this key in a row

  • FireFox passes in “KeyEvents” containing the “initKeyEvent()” method

3. Simulate other events

  • The incoming”HTMLEvents“, using the return objectinitEvent()Method to initialize

4. Customize DOM events

  • Pass createEvent(“CustomEvent”) and return an object containing the initCustomEvent() method, receiving the following arguments:

    • Type: Indicates the type of event to be emitted, such as myevent

    • Bubbles: indicates whether an event bubbles

    • Cancelable: indicates whether the event can be cancelled.

    • Detail: Any value used as the detail property of the event object.

2. IE event simulation

  • createEventObject()Creating an Event Object
  • Manually set the properties of the Event
  • Called on the event targetfireEvent()Method to receive parameters
    • The name of the event handler
    • The event object