js event of web interaction

Preface

The event is used to realize the interaction between js and html, you can use a listener (or handler) to subscribe to the event so that the corresponding code can be executed when the event occurs. This model, known as the observer pattern in traditional software engineering, supports the loose coupling of page behavior (js) and page appearance (html and css). The incident first appeared in IE3 and Netscape Navigator2, as a means of sharing the server's computing load.

1. Event flow

The event flow describes the order in which events are received from the page. The event stream of IE is an event bubbling stream, while the event stream of Netscape Communicator is an event capture stream.

1. Event bubbling

IE's event flow is called event bubbling, that is, the event is received by the most specific element (the node with the deepest nesting level in the document) at the beginning, and then propagated up to the less specific node (document). For example, if you click the <div> element in the page, the click event will propagate upwards in the following order until it reaches the document object.

js event of web interaction

Note: All modern browsers support event bubbling, but there are still some differences in specific implementation. Event bubbling in IE5.5 and earlier versions will skip the <html> element (from <body> to document). Firefox, Chrome, and Safari bubble events all the way to the window object.

2. Event capture

The idea of ​​event capture is that less specific nodes should receive the event earlier, and the most specific node should receive the event last. The purpose of event capture is to capture the event before it reaches the predetermined target. The event capture process of the previous example is:

js event of web interaction

3. DOM event flow

The event flow specified by "DOM2 Level Event" includes three stages: the event capture stage, the target stage and the event bubbling stage. Similarly, the sequence of triggering events in the previous example is:

js event of web interaction

IE9, Opera, Firefox, Chrome and Safari all support DOM event stream; IE8 and earlier versions do not support DOM event stream.

Two, event handler

An event is an action performed by the user or the browser itself. The function that responds to an event is called an event handler (or event listener). The name of the event handler starts with "on", for example, the event handler for the click event is onclick. There are several ways to specify handlers for events.

1. HTML event handler

Event handlers defined in HTML can contain specific actions to be executed, or they can call scripts defined elsewhere on the page.

<input type="button" value="Click Me" οnclick="alert(this.value)" />  

or

<script type="text/javascript">    
    function showMessage(){    
        alert("Hello world!");    
    }    
  </script>    
  <input type="button" value="Click Me" οnclick="showMessage()" />  

Note: You can no longer use unescaped HTML syntax characters, such as ampersand (&), double quotes (""), less than (<) or greater than (>).

There are three disadvantages to specifying event handlers in HTML. 1. There is a jet lag problem. Because the user may trigger the corresponding event as soon as the HTML element appears on the page, but the event handler at that time may not have the execution conditions. For this reason, many HTML event handlers will be encapsulated in a try-catch block so that errors will not surface. 2. In this way, expanding the scope of the event handler will lead to different results in different browsers. Different js engines follow slightly different identifier resolution rules, and errors may occur when accessing unqualified object members. 3. HTML and js code are tightly coupled, and the event handler has been changed greatly.

2. DOM0 level event handler

The traditional way to specify event handlers through JavaScript is to assign a function to an event handler attribute. This method of assigning values ​​to event handlers appeared in the fourth generation of Web browsers, and is still supported by all modern browsers. The first reason is its simplicity, and the second is its cross-browser advantage.

Each element has its own event handler attributes, such as onclick, etc. You can assign a function to the event handler attribute of the element through js. In the DOM0 event handler, this in the event handler points to the current element.

var objlogo=document.getElementById("site_nav_top");
objlogo.οnclick=function(){
alert(this.innerHTML);//代码改变世界
}

To delete the DOM0 event, simply assign the value of the event handler to null.

objlogo.οnclick=null;

3. DOM2 level event handler

"DOM2 level event" defines two methods, addEventListener() and removeEventListener(), both of which accept 3 parameters: the name of the event to be processed, the function as the event handler, and a Boolean value. If the last Boolean parameter is true, it means that the event handler is called in the capture phase; if it is false, it means that the event handler is called in the bubbling phase. addEventListener() can add multiple event handlers to the element, which will be called in sequence when triggered. removeEventListener() cannot remove anonymously added functions.

var btn = document.getElementById("myBtn");  
btn.addEventListener("click", function(){  
alert(this.id);  
}, false);  
var handler = function(){  
alert("Hello world!");  
};  
btn.addEventListener("click", handler, false);  
// 这里省略了其他代码  
btn.removeEventListener("click", handler, false); // 有效!

The above code will display id first, then hello world. In most cases, the event handler is added to the bubbling phase of the event stream, so as to maximize compatibility with various browsers. IE9, Opera, Firefox, Chrome and Safari all support DOM2 level event handlers.

4. IE event handler

IE implements two methods similar to those in DOM: attachEvent() and detachEvent(). These two methods accept the same two parameters: event handler name and event handler function. Since IE only supports event bubbling, event handlers added by attachEvent() will be added to the bubbling phase.

In the case of using the DOM0 level method, the event handler will run in the scope of the element to which it belongs; in the case of using the attachEvent() method, the event handler will run in the global scope, so this is equal to window. And, unlike the DOM method, these event handlers are not executed in the order in which they were added, but triggered in the reverse order.

Note: 1. There is an on prefix in front of the event name; 2. In the function of the event handler, this no longer points to the current element, but to the window object.

var btn = document.getElementById("myBtn");  
var handler = function(){  
alert("Clicked");  
};  
btn.attachEvent("onclick", handler);  
// 这里省略了其他代码  
btn.detachEvent("onclick", handler); 

Browsers that support IE event handlers are IE and Opera.

5. Cross-browser event handler

The first method to be created is addHandler(). Its responsibility is to use DOM0-level methods, DOM2-level methods or IE methods to add events depending on the situation. It belongs to an object called EventUtil. The addHandler() method accepts 3 parameters: the element to be operated, the event name, and the event handler function. The usage of EventUtil is as follows:

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 {    
            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 {    
            element["on" + type] = null;    
        }    
    }    
}; 

Examples of using EventUtil objects are as follows:

var btn = document.getElementById("myBtn");  
var handler = function(){  
    alert("Clicked");  
};  
EventUtil.addHandler(btn, "click", handler);  
// 这里省略了其他代码  
EventUtil.removeHandler(btn, "click", handler); 

6. Scope of event callback function

When the event is bound to a function, the function will be executed with the current element as the scope.

(1) Use anonymous functions

We wrap an anonymous function for the callback function. After wrapping, although the scope of the anonymous function is pointed to the event trigger element, the content of the execution is just like a direct call, without affecting its scope.

(2) Use the bind method

The use of anonymous functions is flawed. Every call is wrapped into the anonymous function, and redundant code is added. In addition, if you want to use removeEventListener to unbind, you need to create another function reference. The Function type provides the bind method, which can bind the scope of the function, no matter where the function is called, it will not change its scope.

Three, event object

When an event on the DOM is triggered, an event object event is generated, which contains all information related to the event.

1. Event objects in the DOM

DOM-compatible browsers will pass an event object into the event handler. The event object contains properties and methods related to the specific event that created it. The types of events that are triggered are different, and the available properties and methods are also different. However, all events will have the members listed in the table below.

js event of web interaction

js event of web interaction

Inside the event handler, the object this is always equal to the value of currentTarget, and target only contains the actual target of the event. If the event handler is directly assigned to the target element, this, currentTarget, and target contain the same value.

2. Event objects in IE

When adding event handlers using DOM0-level methods, the event object exists as an attribute of the window object. If it is an event handler specified by HTML features, then the event object can also be accessed through a variable named event (the same as the event model in the DOM). IE's event object also contains properties and methods related to the event that created it.

js event of web interaction

3. Cross-browser event object

Comprehensively consider the event objects in DOM and IE, write out cross-browser event objects, and put them in the previous EventUtil.

var EventUtil = {    
    addHandler: function(element, type, handler){    
        // 省略了其他代码    
    },    
    getEvent: function(event){    
        return event? event: window.event;    
    },    
    getTarget: function(event){    
        return event.target || event.srcElement;    
    },    
    preventDefault: function(event){    
        if (event.preventDefault){    
            event.preventDefault();    
        } else {    
            event.returnValue = false;    
        }    
    },    
    removeHandler: function(element, type, handler){    
        // 省略了其他代码    
    },    
    stopPropagation: function(event){    
        if (event.stopPropagation){    
            event.stopPropagation();    
        } else {    
            event.cancelBubble = true;    
        }    
    }    
}; 

Four, event type

There are many types of events that can occur in a web browser. As mentioned earlier, different event types have different information, and the "DOM3 level event" defines the following types of events:
UI events: triggered
when the user interacts with elements on the page; mouse events: when the user moves on the page with the mouse Triggered when an operation is performed on the upper;
wheel event: triggered when the mouse wheel (or similar device) is used;
text event: triggered when text is entered in the document;
keyboard event: triggered when the user performs an operation on the page through the keyboard;
composite event : Triggered when a character is input for IME (Input Method Editor);

Mutation event: Triggered when the underlying DOM structure changes.

1, UI case

(1) Load event: load can be used to determine that the image is loaded. Note: The newly created image element does not start downloading when it is loaded into the page, but starts downloading after setting src. load can be used to determine the completion of js loading. The <script> element can trigger the load event to determine whether the dynamically loaded js file is loaded. It is different from img, the src attribute must be set and added to the document before downloading starts.

(2).unload event

(3).
Resize event Note: Different browsers have different mechanisms regarding when the resize event will be triggered. IE, Safari, Chrome, and Opera will trigger the resize event when the browser window changes by 1 pixel, and then repeat the trigger as the change occurs. Firefox will only trigger the resize event when the user stops resizing the window.
(4).scroll event

2. Focus event

Focus events are triggered when a page element gains or loses focus. Using these events and in conjunction with the document.hasFocus() method and document.activeElement property, you can know the whereabouts of the user on the page. There are the following 6 focus events: blur, DOMFocusIn, DOMFocusOut, foucs, focusin, focusout.

3. Mouse and wheel events

DOM3 level events define 9 mouse events: click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup.
There is also a mousewheel event in the mouse event.
(1). Client area coordinate position: clientX and clientY attributes.
(2). Page coordinate position: pageX and pageY attributes.
(3). Screen coordinate position: screenX and screenY attributes.
(4). Modification keys: shiftKey, ctrlKey, altKey, metaKey.
(5). Related elements: DOM provides information about related elements through the relatedTarget attribute of the event object. In IE, when the mouseover event is triggered, fromElement saves the related elements, and when the mouseout event is triggered, toElement saves the related elements.
(6). Mouse button

(7). More event information

(8). Mouse wheel event: mousewheel event contains wheelDelta attribute, Firefox supports similar DOMMouseScroll event, including detail attribute.

4. Keyboard and text events

The DOM3 level contains 3 keyboard events: keydown, keypress, and keyup.
1. Key code: keyCode attribute
2. Character code: charCode attribute
3. DOM3 level changes: new attributes (key, char, location attributes: indicate which key is pressed), getModifierState() method.
4. textinput event: data attribute: represents the character entered by the user (not the character encoding), inputMethod attribute: represents the way to input text into the text box.

5. Compound event: a type of event used to process the input sequence of IME. 6. Change events: delete nodes, insert nodes, etc. 7, HTML5 events

1. contextmenu event: used to indicate when the context menu should be displayed.
2.Beforeunload event: It is possible for developers to prevent this operation before the page is unloaded.
3. DOMContentLoaded event: triggered after the formation of a complete DOM tree.
4. Readystatechange event: provides information related to the loading state of the document or element.
5. pageshow and pagehide events: pageshow event is triggered when the page is displayed, pagehide event is triggered when the browser unloads the page.
6.hashchange event: to notify developers when the parameter list of the URL changes.

8. Equipment events

1.orientationchange event
2.MozOrientation event
3.deviceorientation event
4.devicemotion event

9. Touch and gesture events

1. Touch event

2. Gesture event

Five, memory and performance

1. Event delegation

Event delegation can solve the problem of too many event handlers in the page. Event delegation utilizes event bubbling, and only one event handler can be specified to handle all events of a certain type.

EventUtil.addHandler(document.body, 'click', function (event) {
  event = EventUtil.getEvent(event);
  var target = EventUtil.getTarget(event);
  switch (target.id) {
  case 'site_nav_top':
    alert('口号');
    break;
  case 'nav_menu':
    alert('点击菜单');
    EventUtil.preventDefault(event);
    break;
  case 'editor_pick_lnk':
    alert('推荐区');
    EventUtil.preventDefault(event);
    break;
  }
});

2. Remove event handler

If a large number of useless event handlers are kept in memory, performance will be affected. So be sure to remove the event handler in time when it is not needed. Pay special attention to the following situations: When using innerHTML to delete an element with an event handler, you must first set the event handler to null. Using delegates can also solve this problem, instead of directly loading the event to the element that will be replaced by innerHTML, but assigning the event to its parent element, which can be avoided. When uninstalling the page, it is best to manually clear all event handlers.

Six, event simulation in DOM

Events are often triggered by user operations or through other browser functions. You can also use JS to trigger specific events at any time, and the events at this time are just like those created by the browser. In testing web applications, simulating trigger events is an extremely useful technique.

1. Events in the DOM

The simulation is divided into three steps:

Use document.createEvent() to create an event object. By assigning different parameters, you can simulate different event types to
initialize event objects;

To trigger an event, call the dispatchEvent() method. All DOM nodes that support the event can support this method.

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

2. Simulate mouse events

First, the input parameter of createEvent() method is "MouseEvent" to simulate mouse events. The returned event object has an initMouseEvent() method to initialize event information. This method has 15 parameters:
type (string): The type of event to be triggered, such as "click".
bubbles(bool): Whether the event is bubbling. Generally set to true.
cancelable(bool): Whether the event can be cancelled. Generally set to true.
view: The view associated with the event, generally set to document.defaultView.
detail (integer): detailed information related to the event, generally set to 0.
screenX: the X coordinate of the event relative to the screen.
screenY: The Y coordinate of the event relative to the screen.
clientX: The X coordinate of the event relative to the viewport.
clientY: The Y coordinate of the event relative to the viewport.
ctrlKey(bool): Whether I pressed the Ctrl key, the default is false.
altKey: Whether the alt key is pressed, the default is false.
shiftKey: Whether the shift key is pressed, the default is false.
metaKey: Whether the meta key is pressed, the default is false.
button (integer): Which mouse button was pressed, the default is 0.
relatedTarget: the object related to the event, generally null. It is only used when simulating mouseover and mouseout.
Finally, call the dispatchEvent() method to the DOM element to trigger the event.

var objmenu = document.getElementById('nav_menu');
objmenu.onclick = function () {
  console.log('menu');
}
document.body.onclick = function () {
  console.log('body');
}
var event = document.createEvent('MouseEvent');
event.initMouseEvent('click', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
for (var i = 0; i < 5; i++) {
  objmenu.dispatchEvent(event);
}

3. Custom DOM events

DOM3 supports custom DOM events. To create a new custom event, you can call the document.createEvent() method. The returned object has an initCustomEvent() method, which contains four parameters:
type: the type of the event that triggered;
bubbles: whether the event bubbling;
cancelable: whether the event Can be canceled;
detail: any value, stored in the event.detail attribute.
Finally, the dispatchEvent() method is called on the DOM element to trigger the event.

var objmenu = document.getElementById('nav_menu');
EventUtil.addHandler(objmenu, 'myevent', function (event) {
  console.log('menu' + event.detail);
});
EventUtil.addHandler(document.body, 'myevent', function (event) {
  console.log('body' + event.detail);
})
if (document.implementation.hasFeature('CustomEvents', '3.0')) {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('myevent', true, true, '测试事件detail');
  for (var i = 0; i < 5; i++) {
    objmenu.dispatchEvent(event);
  }
}

The functions of custom events are Event, CustomEvent and dispatchEvent. Directly customize the event, use the Event constructor; CustomEvent can create a more highly customized event, and can also attach some data, the specific usage is as follows:

var myEvent = new CustomEvent(eventname, options);

The options can be:

{
    detail: {
        ...
    },
    bubbles: true,
    cancelable: false
}

Among them, detail can store some initialization information, which can be called when triggered. Other attributes are to define whether the event has bubbling and other functions. Built-in events will be triggered by the browser based on certain operations, and custom events need to be triggered manually. The dispatchEvent function is used to trigger an event:

element.dispatchEvent(customEvent);

The above code indicates that the customEvent event is triggered on the element. The combination is:

// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });
// create and dispatch the event
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchEvent(event);

You need to pay attention to compatibility issues when using custom events, while using jQuery is much simpler:

// 绑定自定义事件
$(element).on('myCustomEvent', function(){});
// 触发事件
$(element).trigger('myCustomEvent');

In addition, you can also pass more parameter information when triggering a custom event:

$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
});
$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});

Guess you like

Origin blog.51cto.com/14954398/2617849