Home > Article > Web Front-end > JavaScript Advanced Programming Event Study Notes_Javascript Skills
Chapter 12 Events
1. Event flow
1.1 Event bubbling (IE event flow)
□Event bubbling (event bubbling), that is, the event starts with the most specific element (in the document The node with the deepest nesting level) accepts it, and then propagates it up to the less specific nodes (documents).
□All browsers support event bubbling. Firefox, Chrome, and Safari bubble events all the way to the window object.
1.2 Event Capture (Netscape Event Streaming)
□ Less specific nodes receive events earlier, while specific nodes receive nodes last.
□Safari, chrome, Opera, and Firefox support it, but capture starts from the window object (the DOM2 level specification starts from the document).
1.3DOM event flow
□ The event flow specified by "DOM2-level events" includes three stages: event capture stage, target stage and event bubbling stage.
□DOM2: The capture phase does not contain actual targets, does not involve event targets, and only provides opportunities for intercepting events.
□Safari, chrome, Firefox and Opera9.5 and above will trigger events on the event object during the capture phase. As a result there are two opportunities to operate events on the target.
□IE does not support DOM event streaming. Other support.
2. Event handler (or event listener)
Definition: A function that responds to an event.
2.1 HTML event handler
□ Each event supported by an element can be specified using an HTML attribute with the same name as the corresponding event handler.
□The function code characters must be HTML escaped.
□ Problems:
◇Time difference problem: When an event is triggered, the event handler may not yet have execution conditions. Use try-catch block encapsulation so errors don't surface.
◇HTML and JavaScript code are tightly coupled.
2.2 DOM level 0 event handler
□DOM level 0 event handler: Assign a function to an event handler attribute. Pros: Simple, cross-browser.
□ This method of event handler will not bind the event until the code is run.
□ Event handlers specified using DOM level 0 methods are considered methods of the element. Event handlers run within the scope of the element; this in the program refers to the current element.
□Delete DOM0 level events: btn.onclick = null; //Delete event handler
2.3 DOM2 level event handler
□addEventListener() and removeEventListener(). Accepts 3 parameters: the name of the event to be handled, the function as the event handler, and a boolean value.
◇If the last Boolean value is true, it means the event handler is called in the capture phase; if it is false, it means the event handler is called in the bubbling phase.
Var btn = document.getElementById("myBtn");
Btn.addEventListener("click",function(){alert(this.id);},false);
□ Use DOM level 2 method The main benefit of adding event handlers is that you can add multiple event handlers. Triggered in order of addition.
□Event handlers added through addEventListener() can only be removed using removeEventListener(); the parameters passed in when removing are the same as those used when adding the handler. That is, anonymous functions cannot be removed.
□Add event handlers to the bubbling phase for maximum compatibility.
□Firefox, Safari, Chrome and Opera support DOM2 level event handlers. IE does not support it and has its own event handler.
2.4 IE event handler.
□ Similar methods to DOM2 in IE: attachEvent() and detachEvent(). Both methods accept the same two parameters: the event handler name and the event handler function.
□IE only supports bubbling, and event handlers added through attachEvent() are added to the bubbling phase.
The event handling function in attachEvent() will run in the global scope, so this is equal to window.
□attachEvent() can also add multiple handlers to elements to trigger in reverse order.
□attachEvent() event can be removed through detachEvent(), but anonymous functions cannot be removed.
2.5 Cross-browser event handler
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{
elmenet["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{
element["on" type] = null;
}
}
};
□This compatibility function does not take into account all the problems of the browser, such as the scope problem in IE.
3. Event object
Definition: When an event in the DOM is triggered, an event object event will be generated. This object contains all information related to the event.
3.1 Event objects in DOM
① DOM-compatible browsers will pass an event object into the event handler (DOM level 0 or DOM level 2). When specified via HTML attributes, the event variable holds the event object.
②All event objects contain the following attributes/methods. P291
□bubbles: Indicates whether the event bubbles, bool.
□cancelable: Indicates whether the default behavior of the event can be canceled, bool.
□currentTarget: The element whose event handler is currently handling events.
□detail: Details related to the event.
□eventPhase: The stage in which the event handler is called: 1. Capture 2. On target 3. Bubbling.
□preventDefault(): Cancel the event default behavior.
□stopPropagation(): Cancel further capturing or bubbling of events.
□target: The target of the event.
□type: The type of event being triggered.
□view: The abstract view associated with the event.
③Inside the event handler:
□The object this is always equal to the value of currentTarget, that is, both this and currentTarget point to the element bound to the event program.
□target only contains the actual target of the event, that is, the element that triggered the event.
④event.preventDefault(): Can cancel the default behavior of a specific event.
⑤event.stopPropagation(): Immediately stop the propagation of events in the DOM.
⑥ Use the eventPhase attribute to determine which stage of the event flow the event is currently in.
3.2 Event object in IE
①Accessing the event object in IE depends on the specified event handler method.
□When using the DOM0 level method to add an event handler, the event object exists as an attribute of the window object.
□Use attachEvent() to add, then an event object is passed in as a parameter. It can also be accessed through window.event.
□When specifying an event handler through HTML attributes, the event object can be accessed through a variable named event.
②All event objects in IE include the following attributes/methods:
□cancelBubble: Default is false, set to true to cancel event bubbling (similar to the stopPropagation() method in DOM)
□returnValue: Default is true, set to false to cancel the default behavior of the event. (Similar to the preventDefault() method in DOM2)
□srcElement: The target of the event (same as the target attribute in DOM2)
□type: The type of event being triggered.
3.3 Cross-browser event object
var eventUtil = {
getEvent : function(event){
Return event ? Event : window.event;
},
getTarget : function (event){
return event.target || event.srcElement;
},
preventDefault : function(event){
if(event.preventDefault){
event.preventDefault() ;
}else{
event.returnValue = false;
}
},
stopPropagation : function(event){
if(event.stopPropagation){
event. stopPropagation();
}else{
event.cancelBubble = true;
}
}
};
4. Event type
□Mouse event, when the user passes the mouse Triggered when an action is performed on the page;
□Keyboard events, triggered when the user performs an action on the page via the keyboard;
□HTML events, when the browser window changes or a specific client/server interaction occurs trigger.
□Mutation event, triggered when the underlying DOM structure changes.
4.1 UI events
UI events are mainly related to element focus and are only supported in DOM-compatible browsers:
□DOMActive: Indicates that the element has been activated by user operation (via mouse or keyboard);
□DOMFocusIN: Indicates that the element has gained focus; it is the ordinary version of the focus event in HTML;
□DOMFocusOut: It indicates that the element has lost focus; it is the ordinary version of the blur event in HTML;
△Because the supported browsers are very Less, not recommended.
4.2 Mouse events
① There are 7 mouse events defined in DOM. All elements on the page support mouse events:
□click: When the user clicks the main mouse button (the button on the left side of the general formula) or presses Triggered when the Enter key is pressed.
□dblclick: Triggered when the user double-clicks the main mouse button (usually the left button).
□mousedown: Triggered when the user presses any mouse button. This event cannot be triggered via the keyboard.
□mouseout: Fires when the mouse pointer is over an element and the user moves it into another element. The newly moved element may be outside the old element, or it may be its child element. Cannot be triggered via keyboard.
□mouseover: Triggered when the mouse pointer is outside an element and then the user moves it within the boundaries of another element for the first time. Not triggered via keyboard.
□mouseup: Triggered when the user releases the mouse button. Not triggered via keyboard.
□mousemove: Triggered repeatedly when the mouse pointer moves inside the element. Cannot be triggered via keyboard.
②Note:
□The click event will be triggered only when the mousedown and mouseup events are triggered successively on the same element. If either mousedown or mouseup is canceled, the click event will not be triggered.
□The same element triggers the click event twice in a row before the dblclick event is triggered.
4.2.1 Client area coordinate position
□Mouse events occur at specific positions in the browser viewport. This location information is stored in the clientX and clientY properties of the event object.
4.2.2 Screen coordinate position
□When a mouse event occurs, there is also a position relative to the entire computer screen. Saved in the screenX and screenY properties of the event object (event).
4.2.3 Modifier keys
□Although mouse events are mainly triggered using the mouse, certain keys on the keyboard can also affect the required operations when the mouse is pressed.
□Modification keys are: Shift, Ctrl, Alt and Meta (cmd key in Apple, windows key in windows).
□ Boolean attributes representing these four keys in the DOM: (in the event of the mouse event) shiftKey, ctrlKey, altKey and metaKey (IE does not support metaKey).
4.2.4 Related elements
When mouseover and mouseout events occur, more elements will be involved. Both events involve moving the mouse pointer from within the bounds of one element to within the bounds of another element.
□DOM provides related element information through the relatedTarget attribute of the evnet object.
□IE does not support the relatedTarget attribute.
◇When the mouserover event is triggered, the relevant elements are saved in the fromElement attribute of IE.
◇When the mouseout event is triggered, IE's toElement attribute saves the relevant elements.
□Compatible method:
var eventUtil = {
getRelatedTarget : function(event){
if(event.relatedTarget){
return event.relatedTarget;
}else if(event .toElement){
return event.toElement;
}else if(event.fromElement){
return event.fromElement;
}else{
return null;
}
}
};
4.2.5 Mouse button
□click event: triggered by clicking the primary mouse button, there is no need to detect key information.
□Mousedown and mouseup events have a button attribute in their event objects to represent the button that is pressed or released.
□Button attribute value in DOM:
◇0 means primary mouse button
◇1Middle mouse button (wheel button)
◇2Secondary mouse button
□Button attribute provided by IE
◇0 No button ◇1 Press the primary key ◇2 Press the secondary key ◇3 Simultaneously primary and secondary ◇4 Middle button ◇5 Primary ◇6 secondary ◇7 Primary and secondary
□Compatible code
getButton : function (event){
if(document.implementation.hasFeature("MouseEvents","2.0")){
return event.button;
}else{
switch(event.button){
case 0 :
case 1 :
case 3 :
case 5 :
case 7 :
return 0;
case 2 :
case 6 :
return 2;
case 4:
return 1;
}
}
}
};
□If the primary key is not pressed or released, opera will not trigger mouseup or mousedown
4.2.6 More event information
□detail attribute in DOM2: the number of clicks on an element, cleared to 0 after leaving the element.
□IE adds more information to the mouse. (Only supported by IE, has no practical value).
4.2.7 Mobile Safari
When developing for Safari on iPhone and Ipod:
□ dblclick event is not supported. Double-clicking a Safari window will zoom in, and there is no way to change that behavior.
□Tap the clickable element to trigger the mousemove event first. If the content changes, no other events will occur. If there is no content change, mousedown, mouseup and click occur at one time.
□The mousemove event will also trigger the mouseover and mouseout events.
4.2.7 Accessibility issues
Screen readers can only trigger events through click. Things to note when using mouse events:
□ Use click events to execute code
□ Do not use onmouseover to display new options to the user. Screen reader won't trigger.
□Don’t use dblclick to perform important operations. The keyboard cannot be triggered.
4.3 Keyboard events
① Support for keyboard events mainly follows DOM level 0. "DOM Level 3" specifies keyboard events.
②3 keyboard events:
□keydown: Triggered when the user presses any key on the keyboard, and if the user presses and holds it down, this event will be triggered repeatedly.
□keypress: Triggered when the user presses a character key on the keyboard. If the user presses and holds the key, this event will be triggered repeatedly.
□keyup: Triggered when the user releases a key on the keyboard.
□Same as mouse events, supports the same modifier keys. Moreover, the keyboard event object also has shifKey, ctrlKey, altKey, and metaKey attributes.
4.3.1 Key code
①When keydown and keyup events occur, the keyCode attribute of the event object will contain a code corresponding to a specific key on the keyboard.
②The keyCode attribute value is the same as the encoding of the corresponding lowercase letters or numbers in the ASCII code. Check table P304
③ Both DOM and IE event objects support the keyCode attribute.
④The following are some special situations that will exist regardless of keydown or keyup events:
□In Firefox and Opera, the keyCode value is 59 when pressing the semicolon key, which is the ASCII value, but IE and Safari return 186, which is the keyboard Key code
□ In previous versions of Safari 3, up, down, left, and right, and page up and down returned a value greater than 6300.
□In versions before Opera 9.5, the keyCode of non-numeric alphabetic keys will be set to ASCII encoding.
□In versions prior to Safari 3, keydown and keyup events would not be triggered by pressing the tab, shift, control or substitution keys.
4.3.2 Character encoding
□The event objects of Firefox, Chrome and Safari support a charCode attribute. This attribute only has a value when keypress occurs, and is the ASCII encoding of the character. The keyCode value at this time may be 0, or it may be the key code pressed.
□IE and Opera save ASCII encoding in keyCode.
□Cross-browser character encoding
var EventUtil = {
//Omitted code
getCharCode: function(event){
if(typeof event.charCode == "number") {
return event.charCode;
}else{
return event.keyCode;
}
},
};
4.3.4 textInput event
□When When the user enters characters in the editable area, the textInput event is triggered.
◇Only the editing area can trigger the textInput event.
◇The event will only be triggered when the user presses a key that can enter actual characters.
◇The event object contains a data attribute to save the characters entered by the user.
□In the first half of 2008, only Safari3 and Chrome support it.
4.3.4 Keyboard events in the device. (omitted)
4.4 HTML events
①Definition: HTML events refer to events that are not necessarily related to user operations.
□Load event:
◇Triggered on the window when the page is completely loaded.
◇Trigger on the frameset when all frames are loaded
◇Trigger on the element when the image is loaded
◇Trigger on the