The interaction between JavaScript and HTML is achieved through the event , which represents a meaningful moment in the document or browser window.
listener (ie handler) that executes only when the event occurs. => Observer Mode => Separation of page behavior (defined in JavaScript) and page presentation (defined in HTML and CSS).
The earliest event was to transfer some form processing work from the server to the browser. DOM2 began to try to standardize DOM events in a logical way. IE8 is the last mainstream browser to use a proprietary event system.
Event stream
Which part of the page has a specific event? When you click a button, you actually click not only the button, but also its container and the entire page.
event stream describes the sequence of page receiving events.
IE supports event bubbling flow, Netscape Communicator supports event capture flow
Event bubbling
It starts with the most specific element and then propagates up to the less specific element (document).
Click event: the clicked element first triggers the click event, and then the click event moves up the DOM tree, triggering in turn on each node that it passes, until it reaches the document object.
Events in modern browsers will bubble up to the window object.
Event capture
The least specific node (document) receives the event first, and the most specific node receives the event last. => before it reaches the final goal.
Click event: First captured by the document element, and then spread down the DOM tree in turn until it reaches the actual target element.
Modern browsers start to capture events from the window object. The DOM2 Events specification stipulates that it starts from the document.
Since older browsers do not support it, is usually recommended to use event bubbling . Event capture can be used in special cases.
DOM event flow
The DOM2 Events specification stipulates that the event flow is divided into three stages: event capture, reaching the target and event bubbling.
- Event capture: occurs first, providing the possibility to intercept events in advance;
- The actual target element receives the event;
- Bubbling: respond to the event at this stage at the latest.
In the DOM event stream, the actual target will not receive events during the capture phase. The next stage will trigger the "target" stage of the event on the actual target element, which is usually considered part of the bubbling phase when the event is processed; then the bubbling phase begins, and the event is propagated back to the document.
Although the DOM2 Events specification makes it clear that the capture phase does not hit the event target, modern browsers will trigger events on the event target during the capture phase. => There are two opportunities to handle the event on the event target.
All modern browsers support the DOM event stream, only IE8 and earlier versions do not support it.
capture phase | | / \ bubbling up
-----------------| |--| |-----------------
| element1 | | | | |
| -------------| |--| |----------- |
| |element2 \ / | | | |
| -------------------------------- |
| W3C event model |
------------------------------------------
Event handler
An event is a certain action performed by the user or the browser. Such as click, load, etc.
The function called in response to the event is called the event handler (or event listener ). The name of the event handler starts with "on".
There are multiple ways to specify event handlers.
HTML event handler
Each event supported by specific elements can be used event handler name (onXXX) in the form of HTML attributes to specify. At this time, the value of the attribute must be JavaScript code that can be executed.
Because the value of the attribute is JavaScript code, you cannot use HTML syntax characters without escaping, such as &, ", <and >. To avoid using HTML entities, you can use single quotes instead of double quotes, or use \" ;.
Event handlers defined in HTML can contain precise action instructions, and can also call scripts defined elsewhere on the page. The code executed as an event handler can access everything in the global scope.
In this manner specified event handlers have some special places :
- A function will be created to encapsulate the value of the property. This function has a special local variable event, the event object;
- In this function, this value is equivalent to the target element of the event;
The scope chain of this dynamically created wrapper function has been extended. => The members of the document and the element itself can be accessed as local variables. This is achieved by using with.
// 实际上的包装函数是onclick属性的值 function () { with(document) { with(this) { // ... HTML事件处理程序属性值 } } }
=> Event handlers can access their properties more conveniently (without this.)
If the element is a form input box, the scope chain will also contain the form element => the code of the event handler can directly access other members in the same form (through the name attribute) without referring to the form element.
Specifying the event handler in HTML has problems :
Timing matters. It is possible that the HTML element has been displayed on the page, but the code of the event handler cannot be executed yet. => Most HTML event handlers will be encapsulated in a try/catch block in order to silently fail in this case.
<input type="button" value="Click Me" onclick="try{doSomething();}catch(ex){}">
- The extension of the scope chain of event handlers may lead to different results in different browsers. There are differences in the rules of identifier parsing in different JavaScript engines => accessing unqualified object members may cause errors.
- Strong coupling between HTML and JavaScript. (If you want to modify, you must modify the code in both HTML and JavaScript)
DOM0 event handler
Assign a function to an event handler attribute (of a DOM element). => simple
To use JavaScript to specify the event handler, you must first obtain the reference object to be operated.
Every element (including window and document) has event handler attributes that are usually lowercase.
The event handler will be assigned after the assignment code runs.
The assigned function is regarded as the method of the element. => The event handler will run in the scope of the element, that is, this is equal to the element.
let btn = document.querySelector('#myBtn');
btn.onclick = function() {
console.log(this.id); // "myBtn"
}
Adding event handlers in this way is registered in the bubbling phase of the event stream.
By setting the value of the event handler attribute to null, you can remove the event handler added through the DOM0 method. (The event handler specified in HTML can also be removed by setting the corresponding attribute to null through JavaScript)
btn.onclick = null;
DOM2 event handler
DOM2 Events defines two methods for the assignment and removal of event handlers: addEventListener() and removeEventListener(). Expose on all DOM nodes.
Receive 3 parameters: event name, event processing function and a Boolean value indicating whether to call the processing function in the capture phase (the default value is false, which is called in the bubbling phase).
This event handler also runs in the scope of the element to which it is attached: this equals the element.
Main advantage : You can add multiple event handlers for the same event. Multiple event handlers to add order triggered.
added through addEventListener() can only be using removeEventListener() and passing in the same parameters as when added. (The event processing function must be the same)
In most cases, the event handler will be added to the bubbling phase of the event stream is that it has good cross-browser compatibility. (Unless the event needs to be intercepted before it reaches its designated target)
IE event handler
IE implements methods similar to DOM, attachEvent() and detachEvent().
Receive 2 parameters: event handler name and event handler function. Because IE8 and earlier versions only support event bubbling, event handlers added using attachEvent() will be added to the bubbling phase.
AttachEvent used in IE () using DOM0 embodiment main difference that the scope of the event handler. uses attachEvent(), the event handler runs in the global scope, so this is equal to window.
The attachEvent() method can also add multiple event handlers to an element. Trigger , in the order in which they were added.
Event handlers added using attachEvent() will be removed using detachEvent(), as long as the same parameters are provided (the processing function is the same function reference).
let btn = document.querySelector('#myBtn');
var handler = function() {
console.log("Clicked");
};
btn.attachEvent("onclick", handler);
btn.detachEvent("onclick", handler);
Cross-browser event handler
Handle events in a cross-browser compatible way.
I write the cross-browser event handling code mainly rely on the capability detection . To ensure maximum compatibility, just let the code run during the bubbling phase.
var EventUtil = {
addHandler: function(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent("on"+type, handler);
} else { // 默认DOM0方式
element["on"+type] = handler;
}
},
removeHandler: function(element, type, handler) {
if(element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if(element.detachEvent) {
element.detachEvent("on"+type, handler);
} else { // 默认DOM0方式
element["on"+type] = null;
}
}
};
// 使用
let btn = document.querySelector('#myBtn');
let handler = function() {
console.log("Clicked");
};
EventUtil.addHandler(btn, "click", handler);
EventUtil.removeHandler(btn, "click", handler);
Unsolved existing problems:
- The scope of IE. (This is equal to window in attachEvent())
- The order of execution of multiple event handlers. DOM2 is in the order of addition, IE is the reverse of the order of addition
- DOM0 only supports adding a handler to an event. (DOM0 browser has been used by few people, the problem should not be big)
Event object
When an event occurs in the DOM, all relevant information (such as event target element, event type) will be collected and stored in an object named event.
DOM event object
In DOM-compliant browsers, the event object is the only parameter passed to the event handler. No matter which method (DOM0 or DOM2) specifies the event handler, this event object will be passed in. In the event handler specified by HTML attributes, the variable event can also be used to refer to the event object.
Public properties and methods included in all event objects:
- bubbles. Boolean value. Bubbling
- cancelable. Boolean value. Is it possible to cancel the default behavior of the event
- currentTarget. element. The element where the current event handler is located
- defaultPrevented. Boolean value. true means that the preventDefault() method has been called. (New in DOM3 Events)
- detail. Integer (??). Other information related to the event
- eventPhase. Integer. Indicates the stage of invoking the event handler: 1-capture stage; 2-reach the target; 3-bubbling stage
- target. element. Event target element
- trusted. Boolean value. True means that the event is generated by the browser; false means that the event is created by the developer through JavaScript. (New in DOM3 Events)
- type. String. Type of event triggered
- View. AbstractView. An abstract view related to the event; equal to the window object where the event occurred
- preventDefault(). function. The default behavior used to cancel the event => callable only when cancelable is true
- stopImmediatePropagation(). function. Used to cancel all subsequent event capture or event bubbling, and prevent any subsequent event handlers from being called. (New in DOM3 Events)
- stopPropagation(). function. Used to cancel all subsequent event capture or event bubbling => Callable only when bubbles is true
Inside the event handler, this is always equal to currentTarget. this === event.currentTarget
.
If the event handler is added directly to the target of the intent, then this, currentTarget and target are equal.
The type attribute is useful when a handler handles multiple events: depending on the type of event, different responses are made.
preventDefault() can prevent the default action of a specific event. For example, the default behavior of a link is to navigate to the URL specified by the href attribute when clicked. For any event that can call preventDefault() to cancel the default behavior, the cancelable property of the event object will be set to true.
stopPropagation() is used to immediately stop the event flow from propagating in the DOM structure and cancel subsequent event capture or bubbling.
The eventPhase attribute can be used to determine the current phase of the event flow. If the event handler is called on the target, eventPhase is equal to 2 => Although "reaching the target" occurred during the bubbling phase, eventPhase is equal to 2. => When eventPhase is equal to 2, this, currentTarget and target are equal.
event object only exists during the execution of the event handler, and once it is executed, it will be destroyed.
IE event object
IE event objects can be in different ways 1609b51a325486 based on the way the event handler is specified
- If specified by DOM0, the event object is an attribute of window
- If specified with attachEvent(), the event object will be passed to the processing function as the only parameter. At this time, the event object is still a property of the window, and it is also passed in as a parameter for convenience
- In the event handler specified by HTML attributes, the variable event can also be used to refer to the event object.
Public properties and methods that all IE event objects will contain:
- cancelBubble. Boolean value. Read/write. true means to cancel the bubbling (default false), similar to the effect of the stopPropagation() method
- returnValue. Boolean value. Read/write. false means to cancel the default behavior of the event (default is true), which has the same effect as preventDefault()
- srcElement. element. Event target, namely target
- type. String. Type of event triggered
The scope of the event handler depends on the way it is specified, so a better way is to use the srcElement property of the event object instead of this. (In DOM0 mode, this is equal to the element; in attachEvent() mode, this is equal to window)
Unlike the DOM, there is no way to determine whether an event can be cancelled through JavaScript.
The cancelBubble attribute is similar to the use of the stopPropagation() method, but IE8 and earlier versions do not support the capture phase, so it will only cancel the bubbling.
Cross-browser event object
The DOM event object contains all the information and capabilities of the IE event object, but the form is different. These commonalities make it possible to map between the two event models.
var EventUtil = {
addHandler: function(element, type, handler) {
// ...
},
removeHandler: function(element, type, handler) {
// ...
},
getEvent: function(event) { // IE事件中以DOM0方式指定事件处理程序时,event对象是window的一个属性
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;
}
},
stopPropagation: function(event) { // 可能会停止事件冒泡,也可能既会停止事件冒泡也停止事件捕获
if(event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
};
// 使用
let btn = document.querySelector('#myBtn');
btn.onclick = function(event) {
event = EventUtil.getEvent(event);
let target = EventUtil.getTarget(event);
EventUtil.preventDefault(event); // 阻止事件的默认行为
EventUtil.stopPropagation(event); // 阻止事件冒泡
};
Event type
The type of event that occurs determines what information will be stored in the event object. Event types defined by DOM3 Events:
- User interface events (UIEvent): general browser events that interact with the BOM
- FocusEvent (FocusEvent): Triggered when an element gains and loses focus
- Mouse Event (MouseEvent): Triggered when the mouse performs certain operations on the page
- WheelEvent: Triggered when the mouse wheel (or similar device) is used
- Input Event (InputEvent): Triggered when text is entered into the document
- Keyboard Event (KeyboardEvent): Triggered when the keyboard performs certain operations on the page
- Composition Event: Triggered when a character is input using a certain IME (Input Method Editor)
- HTML5 also defines another set of events
- Browsers usually implement proprietary events on DOM and BOM: according to the needs of developers, different browsers may implement different
DOM3 Events redefines events on the basis of DOM2 Events and adds new event types. All major browsers support DOM2 Events and DOM3Events.
User interface event UIEvent
Not necessarily related to user operations. They are reserved for backward compatibility. There are mainly the following:
- DOMActivate (deprecated in DOM3 Events). The element is triggered when the user activates it through a mouse or keyboard operation, there are differences between browser implementations
- load. window (triggered after the page is loaded); window frameset (triggered after all the pane frames are loaded); img (triggered after the image is loaded); object (triggered after the corresponding object is loaded)
- unload. window (triggered after the page is completely uninstalled); window cover (triggered after all the panes are uninstalled); object (triggered after the corresponding object is uninstalled)
- abort. object (triggered when the user terminates the download before the corresponding object is loaded)
- error. window (triggered when a JavaScript error is reported); img (triggered when the specified image cannot be loaded); object (triggered when the corresponding object cannot be loaded); window cover (triggered when one or more panes cannot be loaded)
- select. Triggered when the user selects one or more characters in the text box (input or textarea)
- resize. window or pane (triggered when the window or pane is zoomed)
- scroll. on the element when the user scrolls containing the scroll bar element 1609b51a325c20. The body element contains the scroll bar of the loaded page
Most HTML events are related to window objects and form controls. Except for DOMActivate, everything else is classified as HTML Events in DOM2 Events. (DOMActivate is a UI event)
FocusEvent
Fires when a page element gains or loses focus. Can be combined with document.hasFocus() and document.activeElement provide developers with user navigation information on the page. There are 6 types of focus events:
- blur. Fires when the focus is lost. No bubbling, all browsers support
- DOMFocusIn (deprecated in DOM3 Events, focusin is recommended). Fires when the focus is acquired. The bubbling version of focus. Opera only supports
- DOMFocusOut (deprecated in DOM3 Events, focusout is recommended). Triggered when the focus is lost, a general-purpose version of blur. Opera only supports
- focus. Fires when the focus is acquired. No bubbling, all browsers support
- focusin. Fires when the focus is acquired. bubbling version of focus
- focusout. Fires when the focus is lost. Universal version of blur
The two main events are focus and blur, and their biggest problem is not bubbling.
When the focus moves from one element A on the page to another element B, the following events will occur in sequence (test, inconsistent with the book):
1)A:blur
2)A:focusout
3)B:focus
4)B:focusin
DOMFocusOut and DOMFocusIn are not verified
Mouse and wheel events MouseEvent
The mouse is the user's main pointing device. DOM3 Events defines 9 mouse events:
- click. Triggered when the user clicks the primary mouse button (usually the left button) or presses the keyboard enter key.
- dblclick. Triggered when the user double-clicks the primary mouse button (usually the left button) (standardized in DOM3 Events)
- mousedown. Triggered when the user presses any mouse button. Cannot be triggered by keyboard
- mouseenter. Triggered when the user moves the mouse cursor from outside the element to the inside of the element. No bubbling, nor will it trigger when the cursor passes over descendant elements. (New in DOM3 Events)
- mouseleave. Triggered when the user moves the mouse cursor from the inside of the element to the outside of the element. No bubbling, nor will it trigger when the cursor passes over descendant elements. (New in DOM3 Events)
- mousemove. Triggers repeatedly when the mouse cursor moves over the element. Cannot be triggered by keyboard
- mouseout. Triggered when the user moves the mouse cursor from one element to another element (external element or child element). Cannot be triggered by keyboard
- mouseover. Triggered when the user moves the mouse cursor from outside the element to the inside of the element. Cannot be triggered by keyboard
- mouseup. Triggered when the user releases the mouse button. Cannot be triggered by keyboard
All elements on the page support mouse events. Except mouseenter and mouseleave, other mouse events will bubble up and can be cancelled, which will affect the default behavior of the browser. Due to the relationship between events, canceling the default behavior of mouse events will also affect other events.
Double-clicking the main mouse button will trigger events in the following order:
1)mousedown
2)mouseup
3)click
4)mousedown
5)mouseup
6)click
7)dblclick
Both click and dblclick rely on other events to trigger before they are triggered, and mousedown and mouseup are not affected by other events.
There is a problem in the implementation of IE8 and earlier versions, which will cause the double-click event to skip the second mousedown and click events.
1)mousedown
2)mouseup
3)click
4)mouseup
5)dblclick
The corresponding type of mouse events in DOM3 Events is "MouseEvent" (singular form)
Mouse events also have a subcategory called wheel events. wheel event has only one event mousewheel , which corresponds to the interaction of the wheel on the mouse wheel or similar devices with a wheel.
mouse event event object:
- Client coordinates
Note: Client coordinates do not consider page scrolling
- Page coordinates
Position on the page. Represents the coordinates of the mouse cursor on the page when the event occurs, and is obtained through the pageX and pageY properties of the event object.
It reflects the distance from the cursor to the page instead of the left and top of the viewport.
- Screen coordinates
The coordinates of the mouse cursor on the screen are obtained through the screenX and screenY properties of the event object.
- Modifier keys
Sometimes to determine the operation that the user wants to achieve, also considers the state of the keyboard keys .
The modifier keys Shift, Ctrl, Alt and Meta (window key for win, command key for mac) on the keyboard are often used to modify the behavior of mouse events.
Four attributes represent the status of these modifier keys: shiftKey, ctrlKey, altKey, metaKey. (When pressed is true, otherwise it is false)
The browser now supports all 4 modifier keys, and IE8 and earlier versions do not support the metaKey attribute.
- Related elements
For mouseover and mouseout events, there other elements related to the event .
- Mouse button
For mousedown and mouseup events, there will be a button attribute event object, which indicates which button was pressed or released. DOM defines 3 values for the button attribute: 0-primary key; 1-middle button (usually the scroll wheel button); 2-secondary button.
IE8 and earlier versions also provide the button attribute, taking into account the situation of pressing multiple keys at the same time.
Extra event information
The DOM2 Events specification provides detail attribute on the event object to give more information about the event. For mouse events, the detail contains a value indicating how many clicks (continuous clicks) have occurred at a given position. Each click will increase by 1. Continue clicking the interrupt will reset to 0.
IE also provides the following additional information for each mouse event:
- altLeft, boolean, whether the left Alt key is pressed (if true, altKey is also true)
- ctrlLeft, Boolean value, whether to press the left Ctrl key (if it is true, then ctrlKey is also true)
- offsetX, the x coordinate of the cursor relative to the boundary of the target element
- offsetY, the y coordinate of the cursor relative to the boundary of the target element
- shiftLeft, boolean, whether the left Shift key is pressed (if it is true, then shiftKey is also true)
Wheel mousewheel event
Triggered when the user uses the mouse wheel, including arbitrary scrolling in the vertical direction. It will be triggered on any element, and (in IE8) will bubble up to the document and (in all modern browsers) window.
The event object contains all standard information about mouse events, in addition to a property called wheelDelta.
In most cases, you only need to know the direction of the wheel, and this can be known by the sign of the wheelDelta value. (Roll forward once +120, roll backward once -120)
Touch screen device
The touch screen usually does not support mouse operation.
- The dblclick event is not supported. (Test one plus three is OK)
- Touching a clickable element on the screen with a single finger triggers the mousemove event. (Testing one plus three does not work) Clickable elements refer to elements that have default actions when clicked (such as links) or elements that have an onclick event handler specified
- The mousemove event will also trigger the mouseover and mouseout events. (Not tested yet)
- The mousewheel and scroll events are triggered when two fingers touch the screen and slide to cause the page to scroll. (Not tested yet)
Accessibility issues
If a web application or website needs to consider people with disabilities, especially users who use screen readers, then mouse events must be used carefully (except for the Enter key, which can trigger the click event, other mouse events cannot be triggered by the keyboard). It is recommended not to use mouse events other than the click event to prompt users or trigger code execution. => Will strictly hinder the use of blind or visually impaired users.
Several accessibility recommendations that should be followed when using mouse events :
- Use the click event to execute code. When using onmousedown to execute code, the application will run faster, but the screen reader cannot trigger the mousedown event
- Don't use mouseover to show users new options. Unable to trigger. Consider keyboard shortcuts
- Do not use dblclick to perform important operations. Can't trigger
For more information on the accessibility of the website, please refer to the WebAIM website.
Keyboard and input events KeyboardEvent
Triggered when the user operates the keyboard. It is largely based on the original DOM0.
DOM3 Events provides a specification for keyboard events that was first fully implemented in IE9, and other browsers have also begun to implement the specification, but there are still many legacy implementations.
Contains 3 events:
- keydown, triggered when a key on the keyboard is pressed, the continuous button will trigger repeatedly
- keypress (DOM3 Events is obsolete, and textInput event is recommended), which is triggered when a key on the keyboard is pressed and a character is generated, and it will be triggered repeatedly when pressed continuously. The Esc key will also trigger (the test will not trigger in Chrome?).
- keyup, triggered when the user releases a key on the keyboard.
All elements support these events. But it’s easiest to see when you type in the text box.
There is only one input event: textInput. is an extension to the keypress event, which is used to more easily intercept text input before the text is displayed to the user. Will trigger before the text is inserted into the text box.
- When the user presses a character key, will trigger the keydown event, then the keypress event, and finally the keyup event. (Keydown and keypress will be triggered before the text box changes, and keyup will be triggered after the text box changes); if you hold down, keydown and keypress will be triggered repeatedly until the key is released.
- When the user presses a non-character key, will trigger the keydown event, and then trigger the keyup event. If you hold it down, keydown will trigger repeatedly until the key is released.
Note: Keyboard events support the same modifier keys as mouse events.
keyboard event event object:
- KeyCode
For keydown and keyup events, the keyCode property of the event object will store a key code.
For letter and number keys, the value of keyCode is consistent with the ASCII code of uppercase letters and numbers. It has nothing to do with whether the Shift key is pressed.
Both DOM and IE event objects support the keyCode attribute
- Character encoding charCode
The keypress event means that the key press will affect the text displayed on the screen. For keys that insert or remove characters, all browsers will trigger the keypress event, and other keys depend on the browser.
The charCode attribute on the event object, this attribute will be set only when a keypress event occurs (this time is equal to the keyCode attribute). Contains the ASCII code corresponding to the key character.
IE8 and earlier versions and Opera use keyCode to convey the ASCII encoding of characters. To obtain the character encoding in a cross-browser manner, must first check whether the charCode attribute has a value, and then use the keyCode if there is no value.
With the letter encoding, you can use the String.fromCharCode() method to convert it into actual characters.
DOM3
The DOM3 Events specification does not specify the charCode attribute, but defines two new attributes, key and char.
The key attribute is used to replace keyCode and contains a string. When a character key is pressed, the key is equal to a text character; when a non-character key is pressed, the value of the key is the key name (such as "Shift" or "ArrowDown")
The char attribute is similar to key when a character key is pressed, and is null when a non-character key is pressed. (Testing the event object of keypress and keydown in Chrome does not have this attribute)
IE supports the key attribute but not the char attribute.
Safari and Chrome support the keyIdentifier attribute (test Chrome does not have this attribute). For character keys, keyIdentifier returns the character code in the form of a string representing the Unicode value in the form of "U+0000".
Because lacks cross-browser support, it is not recommended to use key, keyIdentifier and char.
DOM3 Events also supports a property named location , which is a numeric value indicating where the key was pressed. The possible values are: 0-default key; 1-left; 2-right; 3-numeric keyboard; 4-mobile device (virtual keyboard); 5-game controller. Safari and Chrome support an equivalent keyLocation property (implementation problem)
not widely supported. It is not recommended to use the location attribute in cross-browser development.
Added the getModifierState() method to the event object , which receives a parameter, a string equal to Shift, Control, Alt, AltGraph, or Meta, indicating the modifier key to be detected. If the given modifier key is buttoned, it returns true. (You can also directly use the shiftKey, ctrlKey, altKey or metaKey attributes of the event object to obtain)
input textInput event
The DOM3 Events specification is newly added, which triggers when a character is input into the editable area.
Compare with keypress: 1. keypress will trigger on any element that can get focus, textInput will only trigger on the editable area; 2. textInput will only trigger when a new character is inserted, and keypress will affect anything that may affect the text All keys will be triggered (including the backspace key (the test in Chrome will not trigger?)). 3. When using the input method (Sogou), the keypress will not be triggered when the synthesis event is triggered, and the textInput event will be triggered before the compositionend is triggered. 4. Use keyboard input to trigger keypress first, and then textInput.
This event mainly focuses on characters. There is a data attribute on the event object, which is the inserted character (non-character encoding); there is also an inputMethod attribute (the test in Chrome does not have this attribute printed as undefined), which represents the means of inputting text into the control , Can assist verification
keyboard events on the device (non-keyboard)
Nintendo Wii
Synthetic event
New in DOM3 Events, used to process complex input sequence when IME input is usually used. IME allows users to enter characters that are not on the physical keyboard. Usually, multiple keys are required to enter a character. Synthetic events are used to detect and control this input.
There are 3 types of synthetic events:
- compositionstart, indicating that the input is about to start
- compositionupdate, which is triggered when a new character is inserted into the input field;
- compositionend, indicating that normal keyboard input is restored
The only event attribute added is data:
- In compositionstart, it is the text being edited (the default is an empty string, or the selected text)
- In compositionupdate, is the new character to be inserted
- In compositionend, all the content entered during this synthesis process
Trigger sequence obtained by the test:
keydown -> ...start -> ...update -> ( (keyup) -> keydown -> ...update -> (keyup) ) (cycle trigger) -> ...update (data Consistent with the data in the ...end event) -> textInput -> ...end -> keyup
Change event
Mutation Events of DOM2 provide notifications when the DOM changes.
(Obsolete)
Has been replaced by Mutation Observers (Chapter 14)
HTML5 events
Some events that are better supported by browsers in HTML5 (not covered by the specification)
- contextmenu event
Click the right mouse button (Ctrl + left click). Used in allow developers to cancel the default context menu and provide a custom menu . bubble.
The event target is the element that triggers the operation. This event can be cancelled in all browsers (event.preventDefault() or event.returnValue is set to false).
The hide (custom menu) is usually triggered by the onclick event handler.
- beforeunload event
Triggered on the window. Used for to provide developers with the opportunity to prevent the page from being uninstalled . Triggered when the page is about to be uninstalled from the browser.
cannot cancel , otherwise it means that users can be permanently blocked on a page.
The event will display a confirmation box to the user. The user can click to cancel or confirm to leave the page. You need to set event.returnValue to the string to be displayed in the confirmation box (for IE and FF) (test FF display prompt text has nothing to do with the returnValue attribute value), and return it as a function value (for Safari and Chrome Say) (Test Chrome has no return value and no effect)
- DOMContentLoaded event
It will be triggered immediately after the DOM tree is built, without waiting for pictures, JavaScript files, CSS files or other resources to load. (You can specify event handlers while downloading external resources, so that users can interact with the page more quickly)
Compare the load event: wait for a lot of external resources to be loaded.
You need to add event handlers to the document or window (the actual event target is the document, which will bubble to the window).
Usually used to add event handlers or perform other DOM operations . This event is always triggered before the load event.
For browsers that do not support the DOMContentLoaded event, you can use the setTimeout() function with a timeout of 0 to set the event handler through its callback. Essentially, this callback is executed immediately after the current JavaScript process is executed. (It is not absolutely certain that the trigger timing is consistent with DOMContentLoaded, preferably the first timeout code on the page)
readystatechange event
IE is first defined. Used for provide document or element loading status information , but the behavior is sometimes unstable.
event.target or other objects that support the readystatechange event have a readyState property, which may have the following 5 values:
- uninitialized: the object exists and has not been initialized
- loading: The object is loading data
- loaded: the object has been loaded with data
- interactive √: The object can be interactive, but has not been loaded yet
- complete √: Object loading is complete
Not all objects will go through all readyState phases (Chrome test document only goes through two phases: interactive and complete)
For the readyState phase with a value of "interactive", the timing is similar to DOMContentLoaded. Entering the interactive phase means that the DOM tree has been loaded. (At this time, pictures and other external resources may not be loaded completely).
When used together with the load event, the trigger sequence of this event cannot be guaranteed. The order of interactive and complete is not fixed. In order to grab an earlier opportunity, it is necessary to detect the interactive phase and the completion phase at the same time (to ensure that the effect of using the DOMContentLoaded event is as close as possible).
pageshow and pagehide events
FF and Opera developed a roundtrip cache (bfcache, back-forward cache) feature called, aims to use the browser "Forward" and expedite the time to switch between pages "back" button . Not only the page data is stored, but the DOM and JavaScript state are also stored. In fact, the entire page is stored in memory.
If the page is in the cache, the load event will not be triggered when navigating to this page.
- pageshow: Triggered when the page is displayed, regardless of whether it comes from the round-trip cache. The newly loaded page will be triggered after the load event; the page from the round-trip cache will be triggered after the page state is fully restored. The event target is document, but the event handler must be added to the window. (Click the "Refresh" button of the browser, the page will reload). The persisted attribute in the event object is a Boolean value, indicating whether the page content comes from the round-trip cache.
- pagehide: After the page is unloaded from the browser, it is triggered before the unload event. The event target is document, but the event handler must be added to the window. The persisted attribute in the event object is a Boolean value, indicating whether the page is saved in the round-trip cache after being unloaded.
registered with the onunload event handler will be automatically excluded from the round-trip cache (testing beforeunload will also affect), because the typical scenario of onunload is to undo what is done when the onload event occurs. If you use the round-trip cache, the next page The onload event will not be triggered when it is displayed, which may cause the page to be unusable.
- hashchange event
Used to notify the developer when the URL hash value (the part after #) changes.
The event handler must be added to the window. The event object has two new attributes: oldURL and newURL, which respectively store the URL before and after the change, and the complete URL containing the hash value. If you want to determine the current hash value, it is best to use the location object.
Equipment event
Smartphones and tablets => a new way of interaction
Used to determine how the user uses the device.
- orientationchange event
Apple, mobile Safari browser. Determine whether the user's device is in vertical mode or horizontal mode. The window.orientation property has 3 values: 0-vertical mode, 90-left-turn horizontal mode (Home button on the right), -90-right-turn horizontal mode (Home button on the left). This event is triggered when the property value changes.
All iOS devices support this event and this attribute. (Test lock vertical screen => will not change)
It is considered to be a window event, and the onorientationchange attribute can also be added to the body element to specify the event handler.
deviceorientation event
The event defined by the DeviceOrientationEvent specification.
If the accelerometer information of the device can be obtained and the data has changed, it will be triggered on the window. It only reflects the orientation of the device in space, and has nothing to do with movement.
The device itself is in a 3D space, the x-axis direction is from the left to the right of the device, the y-axis direction is from the bottom to the top of the device, and the z-axis direction is from the back to the front of the device.
The event object contains the changes of each axis relative to the coordinate value of the device when it is static, and it has 5 main attributes:
- Alpha: a floating point value between 0 and 360, representing the degree of the y-axis when rotates around the z-axis and
- beta: A floating point value within -180~180, which means the degree of the z-axis when rotates around the x-axis and
- gamma: a floating-point value in the -90 to 90, represents about the y-axis Z axis when the degree (torsion).
- absolute: Boolean value, indicating whether the device returns an absolute value.
- compassCalibrated: Boolean value, indicating whether the compass of the device is correctly calibrated.
Test iPhone8 (iOS11.4.1) flat on the desktop and keep listening to changes (?), test Android (one plus three) flat on the desktop will not change
devicemotion event
The event defined by the DeviceOrientationEvent specification.
Used to indicate that the device is actually moving, not just changing its orientation. The extra attributes contained in the event object:
- acceleration: object, including x, y, and z attributes, reflecting acceleration information in all dimensions without considering gravity
- accelerationIncludingGravity: object, including x, y, and z attributes, reflecting acceleration information in various dimensions, including the natural acceleration of gravity on the z axis
- interval: milliseconds, the time from the next trigger event. This value should be constant between events.
- rotationRate: object, including alpha, beta, and gamma attributes, indicating the orientation of the device.
If the acceleration, accelerationIncludingGravity, and rotationRate information cannot be provided, the attribute value is null. => It must be tested before use
Test iPhone8 (iOS11.4.1) flat on the desktop and keep monitoring until changes, test Android (one plus three) flat on the desktop and keep monitoring until changes
Touch and gesture events
Only applicable to touch screen devices.
Webkit customized many proprietary events for Android, which became the de facto standard and was included in the W3C Touch Events specification.
Touch event
The following types:
- touchstart: triggered when the finger is placed on the screen
- touchmove: Triggered continuously when the finger slides on the screen. Call preventDefault() in this event to prevent scrolling (testing does not)
- touchend: triggered when the finger is removed from the screen
- touchcancel: Triggered when the system stops tracking touches. The document does not specify under what circumstances to stop tracking.
Both bubbling and all can be cancelled. They are not part of the DOM specification, and browsers implement them in a DOM-compatible way. The event object of each touch event provides the common attributes of mouse events, and provides the following 3 attributes for tracking touch points:
- touches: An array of Touch objects, representing each touch point on the current screen.
- targetTouches: An array of Touch objects, representing the touch points specific to the event target.
- changedTouches: an array of Touch objects, representing the touch points that have changed since the last user action
Each Touch object contains some attributes, which can be used to track the touch track on the screen. (For a touch point) When the touchend event is triggered, there is nothing in the touches collection. This is because there are no scrolling touch points.
When a finger touches an element on the screen, the events that are triggered in sequence (the test is inconsistent with the book):
1)touchstart
2)touchend
3)mousemove
4)mousedown
5)mouseup
6)click
Gesture event
Added in Safari in iOS2.0. Triggered when two fingers touch the screen and the relative distance or rotation angle changes. There are three types:
- Gesturestart: trigger when one finger is on the screen and another finger is placed on the screen
- Gesturechange: trigger when the position of any finger on the screen changes
- Gestureend: Triggered when one of the fingers leaves the screen
Will bubbling.
These events are only triggered when two fingers touch the event receiver at the same time (within the boundary of the target element).
There is a certain relationship between touch events and gesture events.
The event object of each gesture event contains all the standard mouse event attributes, and two new attributes are rotation and scale.
rotation: indicates the degree of rotation of the finger, a negative value indicates a counterclockwise rotation, a positive value indicates a clockwise rotation (starting from 0);
Scale: Indicates the degree of distance change (pinching) between the two fingers. It is 1 at the beginning, and then increases or decreases as the distance increases or decreases.
The touch event also returns the rotation and scale properties, but they only change when two fingers touch the screen.
Browser events defined in some other specifications
Reference book
Memory and performance
In JavaScript, the number of event handlers in a page is directly related to the overall performance of the page.
First, each function is an object, all take up memory space; secondly, to specify the number of accesses DOM event handlers will be required advance cause delays entire page interaction.
Improve page performance?
Event delegation
The solution to "too many event handlers" is to use event delegation.
uses event bubbling to manage one type of event using only one event handler. As long as you add an event handler to the common ancestor node of all elements (elements that need to handle certain events), the problem can be solved (different processing according to the target judgment). => Only one DOM element was accessed and an event handler was added. => occupies less memory, all events using buttons (most mouse events and keyboard events) are suitable for this solution.
As long as it is feasible, you should consider adding only one event handler to the document, which handles all events of a certain type in the page. The advantages are as follows:
- The document object is available at any time. => As long as the page renders clickable elements, it can work without delay.
- It can save both DOM references and time (setting the event of the page event handler).
- Reduce the memory required for the entire page and improve overall performance.
The most suitable events for using event delegation include: click, mousedown, mouseup, keydown, and keypress.
Delete event handler
After the event handler is assigned to the element, a connection is established between the browser code and the JavaScript code responsible for page interaction. The more this connection is established, the worse the page performance will be. In addition to using event delegation to reduce this connection, you should also delete unused event handlers in a timely manner.
The poor performance of many web applications is caused useless event handler of long-resident memory 1609b51a339e22. The reasons are as follows:
- Delete elements with event handlers. For example, use the method removeChild() or replaceChild() to delete a node, or use innerHTML to replace a part of the page as a whole. => If there is an event handler on the deleted element, it will not be cleaned up normally by the garbage collector. (Especially IE8 and earlier versions, element references and event handler references)
If you know an element is deleted, it is best to remove it before manually delete its event handler (or do not give it to add an event handler directly, using the event delegate). => Make sure that the memory is reclaimed and the element can be safely deleted from the DOM.
Note: Deleting the element in the event handler will prevent the event from bubbling up. The event will only bubble up if the event target still exists in the document.
- Page unloading results in residual references in memory. The event handler has not been cleaned up and will remain in memory.
It is best to delete all event handlers in the onunload event handler before the page is unloaded. => Advantages of using event delegation: very few event handlers.
Simulated event
Usually events are triggered by user interaction or browser functions.
Any event can be triggered at any time via JavaScript => especially useful when testing web applications
The DOM3 specification specifies the way to simulate certain types of events.
DOM event simulation
step:
Use the document.createEvent() method to create an event object.
The createEvent() method receives one parameter, a string indicating the type of event to be created. DOM2 is the English plural form, and DOM3 is the English singular form. The available values are one of the following:
- "UIEvents" (DOM3 is "UIEvent"): General user interface events (mouse events and keyboard events are inherited from here)
- "MouseEvents" (DOM3 is "MouseEvent"): general mouse events
- "HTMLEvents" (not available in DOM3): general HTML events (already distributed to other event categories)
- Keyboard events (added in DOM3 Events)
- "Events": General events
- "CustomEvent" (added in DOM3): custom event
- Use event-related information to initialize
Each type of event object has a specific method, depending on the parameters passed in when calling createEvent()
- trigger event
The event target calls the dispatchEvent() method. This method exists on all DOM nodes that support events.
Receive a parameter, the event object to trigger the event
- Bubbling and trigger event handler execution
Simulation of different event types:
Mouse event
- Call createEvent() and pass in the "MouseEvents" parameter
- Call the initMouseEvent() method of the returned event object to specify specific mouse information for the new object. Receive 15 parameters, corresponding to the attributes exposed by the mouse event, such as type, bubbles, cancelable, view, etc. These four are the only important parameters for the correct simulation of events, because the browser needs to use them, and the other parameters are events To be used by the handler.
- The target attribute of the event object is automatically set to the node that calls the dispatchEvent() method
All mouse events can be simulated in DOM compliant browsers
Keyboard events
- The way to create keyboard events in DOM3 is to pass in the parameter "KeyboardEvent" to the createEvent() method
- Call the initKeyboardEvent() method of the returned event object. Receive 8 parameters, including type, bubbles, cancelable, view, etc.
The keypress event is discarded in DOM3 Events, so the keydown and keyup events can only be simulated in the above way.
Before using
document.createEvent("KeyboardEvent")
, it is best to check the browser’s support for DOM3 keyboard eventsdocument.implementation.hasFeature("KeyboardEvents", "3.0")
.To test Chrome, the key and modifier parameters passed by calling the initKeyboardEvent() method are inconsistent with the attributes printed in the event handler. You can use
new KeyboardEvent()
(the parameters are the same as those printed in the event handler). In addition, both simulations are both Will not make the text box have contentFF limit:
- Pass in "KeyEvents" to createEvent() to create keyboard events
- Call the initKeyEvent() method of the event object. Receive 10 parameters, including type, bubbles, cancelable, view, etc.
Test: ff (88.0) shows that Uncaught DOMException: Operation is not supported
Other browsers that do not support keyboard events:
- Create a general event and pass in the parameter "Events" to the createEvent() method
- Call the initEvent() method of the event object
- Specify keyboard-specific information through event.xxx
You must use general events instead of user interface events, because user interface events are not allowed to directly add attributes to the event object
Other events
HTML events:
- Call the createEvent() method and pass in "HTMLEvents"
- Call the initEvent() method of the returned event object to initialize the information
Test: Simulate focus, the event can be monitored, but there is no cursor
Custom DOM events
DOM3 adds custom event types. Does not trigger native DOM events.
- Call createEvent() and pass in the parameter "CustomEvent"
- Call the initCustomEvent() method of the returned event object and receive 4 parameters: type, bubbles, cancelable, detail
- Call dispatchEvent()
IE event simulation
Simulate events in IE8 and earlier versions.
step:
- Use the createEventObject() method of the document object to create an event object. No parameters are received, and a general event object is returned
- Manually assign all the attributes that you want the object to have to the returned object. (No initialization method) Any attribute can be specified, including attributes not supported by IE8 and earlier versions. These property values are not important to the event, only the event handler will use them.
- Call the fireEvent() method on the event target. Receive 2 parameters: the name of the event handler and the event object. The srcElement and type attributes are automatically assigned to the event object.
All events supported by IE can be simulated in the same way.
summary
The most common events are defined in the DOM3 Events specification or HTML5.
Need to consider memory and performance issues:
Limit the number of event handlers on the page. => Avoid taking up too much memory and causing slow page response, making it easier to clean up
- Use event delegation
- Clean up related event handlers before the page is uninstalled or elements are deleted from the page
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。