JS Study Notes (13) Events

JS Study Notes (13) Events

Article directory


       The interaction of JS and HTML is achieved through events, which can be subscribed to with listeners (handlers) that execute only when the event occurs. In the field of traditional software engineering, this model is called "observer mode", which can also separate page behavior from page display.

Three elements of the event:

  • Event source: the object on which the event was triggered
  • Event type: how to trigger what event (such as: mouse over trigger or keyboard press trigger)
  • Event handler: done via a function assignment method

 

1. Event flow

Event flow describes the order in which events are received by the page

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        <div id="myDiv">Click Me</div>
    </body>
</html>

 

1.1 Event bubbling

       The IE event flow is called event bubbling because events are defined to start firing from the most specific element (deepest node in the document tree) and propagate upwards to less specific elements (document)

After the civ above is clicked, the order of click events occurs:

       

1.2 Event capture

       The least specific nodes receive events first, and the most specific nodes receive events last. Event capture is actually to intercept events before they reach their final destination.

       After the civ above is clicked, the order of click events occurs:

       

1.3 DOM event flow

       DOM2 Event stipulates that the event flow is divided into three stages: event capture, reaching the target, and event bubbling

       

2. Event handler (event listener)

Event handler names start with on
       

2.1 HTML event handlers (deprecated)

       Each event supported by a particular element can be specified as an HTML attribute using the event handler's name.

       Note: Because the value of the attribute is JS code, you cannot use HTML statements without escaping, such as ampersand (&), double quotes, and greater than or less than signs. To avoid HTML entities, you can use single quotes instead of double quotes

<script>
    function showMessage() {
      
      
        console.log("Hello World!");
    }
</script>
<input type="button" value="Click me" onclick="showMessage()">

       An event handler specified by calling a function first creates a function to encapsulate the property's value. This function has a special local variable event, which holds the event object . The scope chain of dynamically created wrapper functions is extended. Members of document and the element itself can be accessed as local variables. Implemented through with, which means that event handlers can access their own properties more conveniently

function() {
    
    
    with(document) {
    
    
        with(this) {
    
    
            // 属性值
        }
    }
}

       

2.1.1 Problems with HTML event handlers

  1. Timing issue

    It is possible that the HTML element has been displayed on the page, the user has interacted with it, and the code of the event handler cannot be executed yet.

  2. Extensions to event handler scope chains can lead to different results in different browsers

  3. Strong coupling of HTML and JS

       

2.2 DOM0 event handler

       The traditional way to specify event handlers in JS is to assign a function to (DOM element) an event handler attribute. All browsers still support this method because of its simplicity.

       To use JS to specify an event handler, you must first obtain a reference to the operation object. Then assign the event handler property to a function

let btn = document.getElementById("myBtn");
btn.onclick = function() {
    
    
	console.log(this.id);
}

       Event handlers run in the scope of the element, i.e. this is equal to the element . Any properties and methods of the element can be accessed through this in the event handler. Adding event handlers in this way is registered in the bubbling phase of the event stream

       Event handlers added via DOM0 can be removed by setting the eventhandler property to null.

       

2.3 DOM2 event handlers

1. addEventListener()和 removeEventListener()

       DOM2 adds two methods for event handler assignment and removal: addEventListener() and removeEventListener() . Receives 3 parameters: event name, event handler function and a Boolean value. true means the event handler is invoked during the capture phase . false means that the event handler is called during the bubbling phase .

let btn = document.getElementById("myBtn");
btn.addEventListener("click",() => {
    
    
  console.log(this.id);
},false);

You can also abstract the method out

let btn = document.getElementById("myBtn");
let handler = function() {
    
    
    console.log(this.id);
}
btn.addEventListener("click",handler,false);

Notice:

  1. The event type inside must be written as a string type, must be quoted, and without on
  2. The same element, the same event can add multiple listeners

 

2. attachEvent registration event

ie9 previously supported

Notice:

  • The event type inside should be on , such as: onclick

 

3. Register event compatibility solution

function addEventListener(element,eventName,fn) {
    
    
  if(element.addEventListener) {
    
    
    element.addEventListener(eventName,fn); //第三个参数默认false
  } else if(element.attachEvent) {
    
    
    element.attachEvent('on'+eventName,fn);
  } else {
    
    
    //相当于element.onclick = fn;
    element['on'+ eventName] = fn;
  }
}

       

2.4 IE event handler

       IE implements methods similar to DOM, namely attachEvent() and detachEvent() . These two methods receive the same two parameters: the name of the event handler and the event handler function . Events added using attachEvent() will be added to the bubbling phase

let btn = document.getElementById("myBtn");
btn.attachEvent("onclick",() => {
    
    
  console.log("clicked"));
});

Notice:

  • The first parameter of attachEvent() is the event name starting with on
  • The main difference between using attachEvent() in IE versus using DOM0 is the scope of the event handler. When using DOM0, this in the event handler is equal to the target element. When using attachEvent(), the event handler is made in the global scope, that is, this is equal to windows
  • attachEvent() can also add multiple event handlers , but the event handlers will fire in reverse order in which they were added.

       

2.5 Cross-Browser Event Handlers

       To ensure maximum compatibility with event handlers, code needs to be run in the bubbling phase

       To implement a cross-browser event handler, addHandler() needs to be created . This method adds event handlers using DOM0, DOM2 or IE methods respectively as needed. This method adds a method on the **EventUtil()** object for cross-browser event handling. Added addHandler() receives 3 parameters: target element, event name and event handler

let btn = document.getElementById("myBtn");
let handler = function() {
    
    
  console.log("clicked");
}
EventUtil.addHandler(btn,"click",handler);

       addHandler() and removeHandler() do not solve all cross-browser consistency issues, such as IE scope issues, multiple event handler execution order issues

       

3. Event object

       When an event occurs in the DOM, all relevant information is collected and stored in an object called event, this object includes some basic information: such as the element that caused the time, the type of event that occurred and any other that may be related to a specific event data
       

3.1 DOM event object

       In DOM-compliant browsers, the event object is the only parameter passed to the event handler. Regardless of which method (DOM0 and DOM2) specifies the event handler, the event object will be passed in

       The public properties and methods contained in the event:

 

(1)target 和 currentTarget

       Inside an event handler, the this object is always equal to the value of currentTarget, and target contains only the actual target of the event. If the event handler was added directly on the intent's target, the values ​​of this, currentTarget, and target are the same.

       If the event handler is added to the parent node of the button, then their values ​​are different

let btn = document.getElementById("myBtn");
document.body.onclick = function(event) {
    
    
  console.log(event.currentTarget === document.body);//true
  console.log(this === document.body);//true
  console.log(event.target === document.getElementById("myBtn")); //true
}

 

The difference between e.target and this

the difference:

  • e.target : which element is clicked to return which element
  • this : Which element is bound to the event, which element will be returned

 

(2) type attribute

Application scenario: handler handles multiple events

(3)preventDefault()

Default action to block specific events. For example, the default behavior of links

(4)stopPropagation()

Used to immediately stop the event flow from propagating in the DOM structure, canceling the capture or bubbling of subsequent events.

(5) eventPhase attribute

Used to identify the current stage of the event flow.

       

3.2 IE event object

       Unlike DOM events, IE events can be accessed in different ways based on how the event handler is specified . If the event handler is specified using the DOM0 method, the event object is just a property of the window object. If the event handler is specified using attachEvent(), the event object will be passed as the only parameter to the handler function, and the event object is still a property of the window object.

       The public properties and methods contained in the IE event object:

 
       The scope of an event handler depends on how it is specified, so the this value is not always equal to the event target. Therefore, it is better to replace this with the srcElement property of the event object .

(1)returnValue

       Equivalent to DOM's preventDefault(), used to cancel the default behavior of a given event. returnValue = false; that is, set to prevent the default action

(2)cancelBubble

       Like DOM's stopPropogation(), it can prevent event bubbling, and stopPropagation() can cancel capture and bubbling

       

4. Event type

DOM3 Event defines the following event types:

  • User Interface Events (UIEvent)
  • Focus Event (FocusEvent)
  • Mouse event (MouseEvent)
  • Wheel event (WheelEvent): use the mouse wheel is triggered
  • Input Event (InputEvent)
  • Keyboard event (KeyBoardEvent)
  • Composition Event (CompositionEvent): Triggered when a character is entered using an IME (Input Method Editor)

       

4.1 User Interface Events

Events are:

  • DOMActive: Triggered when the element is activated, it is abolished in DOM3
  • load: Triggered on the window when the page is loaded, on the window cover ( <frameset>) when all the panes ( <frame>) are loaded, on <img>the element when the picture is loaded, and on <object>the element when the corresponding object is loaded.
  • unload: Triggered when the page is completely unloaded on the window, triggered when all panes are unloaded on the window cover, triggered when the <object>corresponding object cannot be loaded on the element.
  • abort: <object>Triggered on an element when the download is prematurely terminated by the user before the corresponding object has finished loading
  • error
  • select: fires when the user selects one or more characters on a textbox (input or textarea)
  • resize: Fires on a window or pane when the window or pane is resized
  • srcoll

(1)load

1. Specify the method of load event

       Most commonly used events. The load event fires after the entire page (including all external resources) has loaded. There are two ways to specify the load event:

  • JS method (recommended)
window.addEventListener("load",(event)=>{
    
    
	...
})
  • <body>Add the onload attribute to the element
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body onload="console.log('hhh')">
</body>
</html>

       

2. The case where the load event will be triggered

  • Images will also trigger the load event, including images in the DOM and images not in the DOM

Assign the element an event handler to execute after loading:

window.addEventListener("load",() => {
    
    
  let image = document.createElement("img");
  image.addEventListener("load", (event) => {
    
    
    console.log(event.target.src);
  });
  document.body.appendChild(image);
  image.src = "smile.gif";
})

Note: It is not necessary to add <img>an element to the document to download an image, as long as the src attribute is set to it, the download will start immediately

  • <script>The element triggers the load event after the JS file is loaded, thereby dynamically detecting it.
window.addEventListener("load",() => {
    
    
  let image = document.createElement("script");
  image.addEventListener("load", (event) => {
    
    
    console.log("loaded!");
  });
  script.src = "example.js";
  document.body.appendChild(script);
})

Note: Unlike pictures, to download JS files, you must specify the src attribute and add <script>elements to the document

  • IE and Opera support <link>triggering the load event

       

(2) unload event

       unload is opposite to the load event, and the unload event will be triggered after the document is written. The unload event is generally triggered when navigating from one page to another , and is most commonly used to clean up references to avoid memory leaks.

       

4.2 Focus event

       Fires when an element gains or loses focus. These events can be used together with document.hasFocus() and document.activeElement to provide developers with information about the user's navigation in the page. There are 6 events:

  • focus: Triggered when the element gets focus. No bubbling , supported by all browsers

  • blur: Triggered when the element loses focus. No bubbling , supported by all browsers

  • DOMFocusIn: Triggered when the element gets focus. bubble. DOM3 obsolete

  • DOMFocusOut: Triggered when the element loses focus. bubbling, DOM3 obsolete

  • focusin: Triggered when the element gets focus. bubble

  • focusout: Triggered when the element loses focus. bubble

       When an element is moved from one element to another on the page, the following events occur in sequence:

  1. focusout
  2. focusin
  3. blur
  4. DOMFocusOut
  5. focus
  6. DOMFocusIn

       

4.3 Mouse and wheel events

9 kinds of mouse events:

  • click: Triggered when the main mouse button (usually the left button) is clicked or the keyboard enter key is pressed
  • dblclick: Triggered when the primary mouse button (usually the left button) is double-clicked
  • mousedown: Triggered by pressing any mouse button , it cannot be triggered by the keyboard
  • mouseup: Triggered when the user releases the mouse button
  • mouseenter: Triggered when the user moves the mouse cursor from outside the element to inside the element. Does not bubble and does not fire when passing through descendant elements
  • mouseleave: Triggered when the user moves the mouse cursor from inside the element to outside the element. Does not bubble and does not fire when passing through descendant elements
  • mousemove: Triggered repeatedly when the mouse cursor moves over the element, it cannot be triggered by the keyboard,
  • mouseout: Triggered when the user moves the mouse cursor from one element to another. The moved element can be an external element of the original element or an internal element of the original element. Can't be triggered by keyboard
  • mouseover: Triggered when the user moves the mouse cursor from outside the element to inside the element. Can't be triggered by keyboard

 
Trigger sequence for mousedown, mouseup, click and dblclick:

  1. mousedown
  2. mouseup
  3. click
  4. mousedown
  5. mouseup
  6. click
  7. dblclick

Wheel events:

       only mousewheel, reflecting the interaction of the scroll wheel on a mouse wheel or similar device with a scroll wheel

       

1. Client coordinates

       Mouse events occur at a certain position in the browser viewport, and the information is stored in the clientX and clientY properties of the event object, indicating the coordinates of the mouse cursor in the viewport when the event occurs

       

2. Page coordinates

       The coordinates of the mouse cursor on the page when the event occurs, pageX, pageY, when the page is not scrolled, pageX, pageY are the same as clientX, clientY

       

3. Screen coordinates

screenX and screenY

       

4. Modifier keys

       Modifier keys: Shift, Ctrl, Alt, Meta are also often used to modify the behavior of mouse events. The states corresponding to the modifier keys in the DOM are: shiftKey, ctrlKey, altKey, metaKey , and the corresponding state of the modifier keys is true when they are pressed

       

5. Related elements

       For mouseout and mouseover, there are other elements related to the event. For mouseover , its goal is to get the cursor element of the tube, and the relevant element is the element that lost the cursor . For mouseout , the main target is the element that lost the cursor, and the relevant element is the element that gained the cursor.

       

6. Mouse buttons

       For mousedown and mouseup events, there will be a button attribute on the event object, indicating which button is pressed or released. DOM defines 3 values ​​for the button attribute: 0 means the primary mouse button, 1 means the middle mouse button, and 2 means the right mouse button

       

7. Additional event information

       DOM2 provides a detail property on the event object, detail contains a value, indicating how many clicks occurred at a given location. Starting from 1, if the mouse moves between mouseout and mouseup, detail is reset to 0

       

8. Touch screen devices

Attention should be paid to the development of touch screen devices:

  • The dblclick event is not supported. Double-clicking the browser zooms in, there is no way to override this behavior
  • A single-finger touch on a clickable element on the screen will trigger the mousemove event. If the operation causes the content to change, no other events will be triggered. If there is no change on the screen, the mousedown, mouseup and click events will be triggered one after another, and the event will not be triggered when the unclickable element is clicked
  • The mousever event also triggers mouseover and mouseout events
  • The mouse wheel and scroll events will be triggered when the two fingers touch the screen and cause the page to scroll

 

9. Forbid the mouse to select text

document.addEventListener("selectstart", (e) => {
    
    
    e.preventDefault();
})

 

10. The difference between mouseenter and mouseover (classic interview questions)

  • mouseover will be triggered when the mouse passes through its own box, and it will also be triggered when it passes through the sub-box, and mouseenter will only be triggered through its own box
  • mouseenter does not bubble, mouseover bubbles
           

4.4 Keyboard and input events

keyboard events

  • keydown: Triggered when the user presses a key on the keyboard, and keeps pressing it will trigger repeatedly
  • keypress: Triggered when a key on the keyboard is pressed and a character is generated, and it will be triggered repeatedly if it is pressed continuously. DOM3 obsolete, recommend textInput. textInput is used to intercept text input more conveniently before the text is displayed to the user, and is triggered before the text is inserted into the text box
  • keyup: Triggered when a key on the keyboard is released

       

1. Keycode

       For keydown and keyup, the keyCode attribute of the event object will save a keycode, corresponding to a pending key on the keyboard.

       

2. Character encoding

​ The value will be set when the keypress event occurs, which is the ASCII code corresponding to the key character

       

3. Changes in DOM3

       DOM3 Events does not specify the charCode attribute, but defines two new attributes, key and char. The key attribute is used instead of keyCode.

       DOM3 Events also supports the location attribute, which is a value indicating where to press the key.

       key, char, keyidentifier and location all lack browser support and are not recommended

       

4. textInput event

       New to DOM3, textInput fires when a character is entered into an editable area. The difference with keypress:

  • keypress will trigger on any element that can get the focus, textInput will only trigger on the editable area
  • textInput will only trigger when a new character is inserted, and keypress will trigger for any key that may affect the text, including the backspace key

       

event.data

       textInput focuses on characters, so the data attribute is provided on the event object , which contains the characters to be inserted

       

event.inputMethod

       The attribute named inputMethod on the event object indicates the means of inputting text to the control:

  • 0: Indicates that the browser cannot determine what input means
  • 1: Indicates the keyboard
  • 2: means paste
  • 3: Indicates drag and drop operation
  • 4: Indicates IME
  • 5: Indicates form options
  • 6: indicates handwriting
  • 7: Indicates voice
  • 8: Indicates the combination method
  • 9: Indicates the script

       

4.5 Synthetic Events

       Added to DOM3 to handle complex input sequences that are typically entered using an IME (Input Method Editor). IMEs allow users to enter characters not found on a physical keyboard. IMEs often require pressing multiple keys simultaneously to enter a character. Synthetic events are used to detect and control this input, and have attribute data:

  • compositionstart: Triggered when the IME's text composition system is turned on, indicating that the input is about to start, including the text being edited
  • compositionupdate: Triggered when a new character is inserted into the input field, contains the new character to be inserted
  • compositionend: Triggered when the IME text composition system is closed, indicating that the normal keyboard input is restored, including all the input content of this composition process

       

4.6 HTML5 Events

1. contentmenu event

       Used to indicate when the context menu (menu shown on right-click) should be shown, allowing developers to cancel the default context menu and provide a custom menu.

       The contentmenu event bubbles, so as long as you assign an event handler to the document, you can handle all events of the same type on the page. Usually custom context menus are displayed through the contentmenu event handler and hidden through the onclick event handler.

The basic code to implement the context menu:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <div id="myDiv">hhh</div>
  <ul id="myMenu" style="position: absolute;visibility:hidden;background-color:silver">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
  </ul>
</body>
</html>
window.addEventListener("load",(event) => {
    
    
  let div = document.getElementById("myDiv");

  div.addEventListener("contextmenu", (event) => {
    
    
    event.preventDefault();
    let menu = document.getElementById("myMenu");
    menu.style.left = event.clientX + "px";
    menu.style.top = event.clientY + "px";
    menu.style.visibility = "visible";
  });

  document.addEventListener("click", (event) => {
    
    
    document.getElementById("myMenu").style.visibility = "hidden";
  })
})

       

2. beforeunload event

       The beforeunload event will be triggered on the window to provide developers with the opportunity to prevent the page from being unloaded. This event fires when the page is about to be unloaded from the browser. If the page is to be used continuously, it does not need to be uninstalled. This event prompts a confirmation box back to the user, the information in which indicates that the browser is about to unload the page, and asks the user to confirm whether he wants to close the page.

       In order to display the confirmation box, you need to set event.returnValue to the string to be displayed in the confirmation box, and return it as the function value

window.addEventListener("beforeunload",(event) => {
    
    
  let message = "hhhhhhhhhhh";
  event.returnValue = message;
  return message;
})

       

3. DOMContentLoaded event

       The DOMContentLoaded event will be triggered immediately after the DOM tree is built , without waiting for other resource files such as images, JS, and CSS to be loaded. Compared with the load event, DOMContentLoaded allows developers to specify event handlers while external resources are being downloaded, so that users can interact with the page faster. The DOMContentLoaded event is always triggered before the load

​ window add event handler ( actual event target is document, but will bubble to window)

       

4. readystatechange event

       Used to provide information about the loading status of a document or element. Every object that supports the readystatechange event has a readyState property with a possible string value that can be listed:

  • uninitialized: The object exists and has not been initialized
  • loading: the object is loading data
  • loaded: the object has been loaded
  • interactive: The object can be interacted with, but has not yet finished loading
  • complete: object loading is complete

       

5. pageshow and pagehide events

       Firefox and Opera developed round-trip caching to speed up switching between pages when using the browser's forward and back buttons. This cache not only stores the page, but also stores the DOM and JS state, actually keeping the entire page in memory. If the page is in the cache, the load event will not be triggered when navigating to the page , but some events are provided to expose the behavior of going to and from the cache.

(1)pageshow

       Fired when the page is displayed, whether or not from the round-trip cache. On a newly loaded page, pageshow fires after the load event; on pages from a round-trip cache, pageshow fires after the page state is fully restored.

Note: Although the target tree document of the event, the event handler must be added to the window

       

(2)pagehide

Fired before the unload event after        the page has been unloaded from the browser , the event handler must also be added to the window

       Both pageshow and pagehide have the attribute persisted , which means true if the page stores the round-trip cache, otherwise it is false . For pageshow, if persisted is true, it means that the page is loaded in the round-trip cache; for pagehide, if persisted is true, it means that the page will be saved in the round-trip cache after unloading. Therefore, persisted is always false the first time pageshow is triggered, and persisted is always true the first time pagehide is triggered.

       

6. haschange event

       Used to notify developers when the URL hash value (the part after the last # of the URL) changes . Because developers often use URL hash values ​​to store state information or route navigation information in Ajax applications

       The haschange event handler must be added to the window , and the event object has two properties: oldURL and newURL. It is used to save the URL before and after the change, and contains the complete URL of the hash value.

       

4.7 Device Events

Used to identify how the user is using the device

1. orientationchange incident

       The Apple formula created the orientationchange event on the Safari browser so that developers can determine whether the user's device is in vertical or horizontal mode. Expose the window.orientation property on the window, there are 3 values:

  • 0: vertical mode
  • 90: Turn left in horizontal mode (home screen key is on the left)
  • -90: turn right in horizontal mode (home key is on the right)

       

2. device orientation incident

       If the accelerometer information of the device can be obtained and the data has changed, this event will be triggered on the window. Note: The deviceorientation event only reflects the orientation of the device in space, and does not involve movement-related information

       When deviceorientation is triggered, the event object will contain the changes in the coordinate values ​​of each axis relative to the device when it is stationary , mainly:

  • alpha: a floating-point value in the range of 0~360, indicating the degree of the y-axis when rotating around the z-axis
  • beta: a floating-point value in the range of -180~180, indicating the degree of the z-axis when rotating around the x-axis
  • gamma: a floating-point value in the range of -90~90, indicating the degree of the z-axis when rotating around the y-axis
  • absolute: Boolean, indicating whether the device returns an absolute value
  • compassCalibrated: Boolean, indicating whether the device's compass is calibrated correctly

 

3. devicemotion event

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

       When a devicemotion event is triggered, the event object contains the following additional properties:

  • acceleration: object, including x, y and z attributes, reflecting the acceleration information of each dimension without considering gravity
  • accelerationIncludingGravity: object, including x, y and z attributes, reflecting the acceleration information of each dimension considering gravity
  • interval: milliseconds, the time until the next devicemotion event is triggered.
  • rotationRate: object, including alpha, beta and gamma attributes, indicating the orientation of the device

       If acceleration, accelerationIncludingGravity and rotationRate information cannot be provided, the attribute value is null. For this reason, before using these attributes, they must first check whether their values ​​are null

       

4.8 Touch and Gesture Events

1. Touch events

       When the finger is placed on the screen, slides on the screen or is removed from the screen, touch events are triggered, and there are the following types:

  • touchstart: Triggered when a finger is placed on the screen (even if a finger is placed on the screen)
  • touchmove: Triggered continuously when the finger slides on the screen, preventDefault() can be used to prevent scrolling
  • touchend: Triggered when the finger is removed from the screen
  • touchcancel: Triggered when the system stops tracking touches.

       These events all bubble and can all be cancelled. The event object of each touch event provides the common properties of the mouse event, in addition to:

  • touches: Array of Touch objects, representing each touch on the current screen
  • targetTouches: Array of Touch objects representing touch points specific to the event target
  • changedTouches: an array of Touch objects, indicating the touch points that have changed since the last user action

Properties of each Touch object:

  • clientX
  • clientY
  • identifier: contact ID
  • pageX
  • pageY
  • screenX
  • screenY
  • target

       When a finger touches an element on the screen, the following events (including mouse events) will occur in sequence:

  1. touchstart
  2. mouseover
  3. mousemove (1 time)
  4. mousedown
  5. mouseup
  6. click
  7. touchend

       

2. Gesture events

       Triggered when two fingers touch the screen and the relative distance or rotation angle changes, there are 3 types:

  • gesturestart: Triggered when a finger is already on the screen and another finger is placed on the screen
  • gesturechange: Triggered when the position of any finger on the screen changes
  • gestureend: Triggered when one of the fingers leaves the screen

       These events fire only when two fingers touch the event receiver at the same time. Because these events bubble up, it is also possible to put event handlers at the document level to handle all gesture events

       The event object of each gesture event contains all mouse event properties. The two new event object properties are: rotation and scale. The rotation attribute indicates the degree of rotation of the finger change. Negative values ​​indicate counterclockwise rotation, and positive values ​​indicate clockwise rotation (starting from 0). The scale attribute indicates the degree of change in the distance between the two fingers. The start is 1, the age distance increases or decreases correspondingly

       

5. Memory and Performance

5.1 Event delegation (emphasis)

       The solution to "too many event handlers": event delegation. Event delegation uses event bubbling to manage a class of events with only one event handler. For example: click event bubbles to document. This means that you can specify an onclick event handler for the entire page, rather than specifying event handlers for each clickable element.

  <ul id="myLinks">
    <li id="go"><a href="#">1</a></li>
    <li id="hi"><a href="#">2</a></li>
    <li id="some"><a href="#">3</a></li>
  </ul>
let list = document.getElementById("myLinks");
list.addEventListener("click", (event) => {
    
    
  let target = event.target;

  switch(target.id) {
    
    
    case "go":
      document.title = 'hhhhhhh';
      break;

    case "hi":
      document.title = 'xixixii';
      break;

    case "some":
      location.href = "http://www.baidu.com";
      break;
  }
})

Advantages of event delegation:

  • The document object is available at any time, which means that event handlers can be added to it at any time (without waiting for DOMContentLoaded or load events). It means that as long as the page renders clickable elements, it can work without delay
  • Save time then setting up page event handlers. Saves DOM references and saves time
  • Reduces the memory required for an entire page, improving overall performance

       

5.2 Removing event handlers

       A lot of poor web application performance is caused by useless event handlers resident in memory. Causes of this problem are:

  1. Removes an element with an event handler. Such as: delete the node by the real DOM method removeChild() or replaceChild(). The most common is that innerHTML replaces a certain part of the page as a whole. At this time, if there is an event handler on the element deleted by innerHTML, it will not be cleaned up normally by the garbage collector

    <div id="myDiv">
        <input type="button" value="click me" id="myBtn">
    </div>
    <script>
        let btn = document.getElementById("myBtn");
        btn.onclick = function() {
            
            
            // 操作
    
            btn.onclick = null; //删除事件处理程序,一定要添加
            document.getElementById("myBtn").innerHTML = "hhhhhh...";
        }
    </script>
    

    When a button is clicked, it removes itself and replaces it with a message to prevent the double click from happening

  2. For page unloading, it is best to delete all event handlers in the onunloaded event handler before the page is unloaded.

6. Simulated events

Arbitrary events can be triggered at any time through JS, especially useful when testing

6.1 DOM event simulation

       At any time, an event object can be created with document.createEvent() . This method receives one parameter: a string representing the type of event to create :

  • "UIEvents" (DOM3 is "UIEvent"): generic user interface events
  • "MouseEvents" (DOM3 is "MouseEvents"): generic mouse events
  • "HTMLEvents" (no DOM3): generic HTML events

       The last step of event simulation is to trigger an event, use dispatchEvent(), and receive a parameter, which is the event object to trigger the event. After dispatchEvent() is called, the event "turns positive", then bubbles and triggers the execution of the event handler

1. Simulate mouse events

       Calling createEvent() with the "MouseEvents" parameter returns an event object that has a **initMouseEvent()** method that specifies mouse-specific information for the new object. initMouseEvent() has 15 parameters:

  • type (string): the type of event to be triggered, such as: click
  • bubbles (bool): Whether the event bubbles. For accurate simulation of mouse events, it should be set to true
  • cancelable (bool): Whether the event can be canceled. For accurate simulation of mouse events, it should be set to true
  • view: The view associated with the event. Basic is always document.defaultView
  • detail (integer): Extra information about the event. Only used 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): whether to press the Ctrl key, default false
  • altkey (boolean): whether to press the Atl key, default false
  • shiftkey (boolean): whether the shift key is pressed, default false
  • metakey (boolean): Whether to press the Meta key, default is false
  • button (integer): Indicates which button was pressed. Default is 0
  • relatedTarget (object): The object related to the event. Only used on mouseover and mouseout

Example of simulating a click event with default values:

let btn = document.getElementById("myBtn");
let event = document.createEvent("MouseEvents");
//初始化
event.initMouseEvent("click",true,true,document.defaultView,0,0,0,0,0,false,false,false,false,0,null);
//触发事件
btn.dispatchEvent(event);

       

2. Simulate keyboard events

       Calling createEvent() and passing in the "KeyboardEvents" parameter returns an event object that has a **initKeyboardEvent()** method. initKeyboardEvent() parameters:

  • type (string): the type of event to be triggered, such as: click
  • bubbles (bool): Whether the event bubbles. For accurate simulation of mouse events, it should be set to true
  • cancelable (bool): Whether the event can be canceled. For accurate simulation of mouse events, it should be set to true
  • view: The view associated with the event. Basic is always document.defaultView
  • key (string): the string code of the pressed key
  • location (integer): The location of the pressed button. 0 is the default key, 1 is the left side, 2 is the right side, 3 is the number pad, 4 is the mobile device (virtual keyboard), 5 is the gamepad
  • modifiers (string): Space-separated list of modifier keys, eg: "shift"
  • repeat (integer): how many times has this key been pressed in succession

Note: DOM3 abolishes the keypress event, so only the above methods can be used to simulate keydown and keyup events

       Firefox allows to pass "KeyEvents" to createEvent() to create, the returned object contains initKeyEvent(), parameters:

  • type (string): the type of event to be triggered, such as: click
  • bubbles (bool): Whether the event bubbles. For accurate simulation of mouse events, it should be set to true
  • cancelable (bool): Whether the event can be canceled. For accurate simulation of mouse events, it should be set to true
  • view: The view associated with the event. Basic is always document.defaultView
  • ctrlkey (boolean): whether to press the Ctrl key, default false
  • altkey (boolean): whether to press the Atl key, default false
  • shiftkey (boolean): whether the shift key is pressed, default false
  • metakey (boolean): Whether to press the Meta key, default is false
  • keyCode (integer): Indicates the key code for pressing or releasing the key, used in keydown and keyup. Default is 0
  • charCode (integer): Indicates the ASCII code of the character corresponding to the pressed key, used in keypress. Default is 0

       

3. Simulate other events

       To simulate HTML events, you need to call createEvent() and pass in the "HTMLEvents" parameter , and return an event object, which has an initEvent() method

       

4. Custom DOM events

       Custom events do not trigger native DOM events. To create a custom event, you need to call createEvent(“CustomEvent”) . The returned object includes the initCustomEvent() method , which receives 4 parameters:

  • type (string): the type of event to trigger, such as: "myevent"
  • bubbles (bool): Whether the event bubbles.
  • cancelable (bool): Whether the event can be canceled.
  • detail (object): any value. As the detail attribute of the event object

       

6.2 IE event simulation

       Use createEventObject() of document to create an object . Unlike DOM, this method does not accept parameters and returns a general event object . Then, manually specify all the properties you want the object to have for the returned object. (no initialization method). Finally, the fireEvent() method is called on the event target , which receives two parameters: the name of the event handler and the event object. When calling fireEvent(), the srcElement and type attributes will be automatically assigned to the event object (other attributes must be specified manually)

Simulate click event:

var btn = document.getElementById("myBtn");
var event = document.createEventObject();

event.screenX =100;
event.screenY =0;
event.clientX =0;
event.clientY =0;
event.ctrlkey =false;
event.altkey =false;
event.shiftkey =false;
event.button =0;

btn.fireEvent("onclick",event);

Guess you like

Origin blog.csdn.net/weixin_45950819/article/details/120718993