Reference: the original cloud.tencent.com/info/ad9898…

Events in javascript

  • Javascript programs use the event-driven design pattern to add event listeners to an element, which will be called when the corresponding event of the element is raised: Events are the basis of javascript and HTML interaction. Any document or browser window interaction must be bound to events.
  • All browsers support DOM0-level event handlers, and with this approach, event handlers run in the scope of elements, so this in programs refers to elements.

How to understand DOM0,DOM2, and DOM3

Document Object Model is a programming language – and platform-independent API(Application Programming Interface), with which programs can dynamically access and modify document content, structure, or display style.

As early as 1988, the W3C association began to develop DOM standards, which can be divided into DOM1,DOM2 and DOM3 versions.

The DOM1 level mainly defines the underlying structure of HTML and XML documents.

The DOM2 and DOM3 levels introduce more interactive capabilities on top of this structure, as well as support for more advanced XML features. For this reason, the DOM2 and DOM3 levels are divided into modules (modules that have some relationship with each other) that describe a very specific subset of the DOM. These modules are as follows:

  1. DOM Level 2 Core: Builds on the Level 1 Core, adding more methods and attributes to the node;
  2. DOM2 view (DOM Level 2 Views) : Defines different Views of the document based on style information;
  3. Dom2-level events (DOM Level 2 Style) : define how to programmatically access and change CSS Style information;
  4. DOM Level 2 Traversal and Range: Introduces a new interface for traversing DOM documents and selecting specific parts of them.
  5. DOM2 HTML (DOM Level 2 HTML) : Builds on Level 1 HTML, adding more properties, methods, and new interfaces.
  6. XPath modules and Load and Save modules have been added to the DOM3 level.

The purpose of DOM levels 2 and 3 is to extend the DOM API to meet all the requirements for manipulating XML, while providing better error handling and feature detection capabilities. DOM0 is an event written directly in HTML via onclick;

DOM2 is bound with addEventListener, and DOM2 is bound with attachEvent in IE. DOM3 is something new.

Level 0 DOM:

The event handler is set to js code strings as HTML property values, such as:

<input id="myButton" type="button" value="Press Me" onclick="alert('thanks');">Copy the code

In JS HTML elements have a corresponding object, the attributes of this object correspond to the properties of that HTML element, so you can use JS code to add event listeners

document.getElementById("myButton").onclick = function () {
        alert('thanks');
}Copy the code

Normally, event listeners that return a value of false prevent the browser from performing the default action.

In both HTML and JS, you assign a function to a document element, and when the event listener function is called, it is called as a method of the element that generated the event, so this refers to the target element (the Input object in the example). Technically, the W3C DOM standard does not support the above primitive way of adding event listeners, which are pre-DOM event models. Although there is no formal W3C standard, this event model is still widely used and is often referred to as level 0 DOM.

The DOM level 2:

Events are not defined in the Level 1 DOM standard, so there is no level 1 DOM event model.

The level 2 DOM defines an event model in addition to some DOM-related operations. The event model under this standard is what we call the Level 2 DOM event model

Event propagation for the level-2 DOM occurs in the Level-2 DOM. When an event occurs on a node, the event handler for the target element is fired, and each ancestor node of the target has a chance to handle that event. Because the event propagation of the level 2 DOM takes place in three stages.



  1. First, in the capturing phase, events propagate from Document objects down the Document tree to nodes. If any of the target’s ancestors specifically registered event-listening functions, these functions will be run during event propagation.
  2. Second, the phase occurs on the target node itself, and the appropriate event listener functions registered directly on the target run.
  3. Third, there is the Bubbling stage, where events propagate upward from the target element back to the Document object (as opposed to capturing). While all events are governed by phases of capturing, not all types of events are bubbling. (Level 0 DOM event model processing without capturing stage)

The event object

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

This includes the elements of the event, the type of the event, and other information related to a particular event.

For example, a mouse action event contains information about the position of the mouse, and a keyboard action event contains information about the key being pressed. All browsers support event objects, but in different ways.

IE’s event flow is bubbling from the inside up, netscape captures from external elements to internal elements; However, DOM2 events specify that the event flow contains three stages: 1: event capture, 2: in the target stage, 3: event bubbling stage (IE8 and earlier versions do not support DOM event flow);

In DOM0, DOM2, and DOM3, the event object is passed in the event function;

<script type="text/javascript"> 
    var p = document.getElementById('p'); 
    p.addEventListener("click".function(){
         console.log(arguments[0]); 
    })
</script>Copy the code

Capturing phase events will spread from Document ->span-> A, then occur in A, and finally bubbling phase events will spread from A ->span-> Document.

Level 2 DOM event listener function registration

In the level 2 event model, you can call the object’s addEventListener() method to set event listeners for elements, That is, it is possible for a function registered through the API of the level 2 DOM to catch events in any of the three stages of event propagation (if event listeners assigned with the two methods of the level 0 DOM cannot catch events in the capturing phase).

  1. The first argument to addEventListener is String, the name of the event type, without the prefix on, so for example to register a click event you pass “click”, not “onclick”
  2. The second argument is the listener function. When called, JS will pass it an Event object, which contains details about the Event. If the stopPropagation() method of this object is called, it will prevent the Event propagation from further propagation (for example, if the Event is caught in the first phase and the Event listener function is run, Event is called. StopPropagation events will not be transmitted again and will go through the second and third stages.
  3. The third argument is Boolean, true means that event listeners can capture events in any of the three phases (compliant with DOM level 2), false means that event listeners cannot capture events in the capturing phase (like DOM level 0).

The level 2 DOM listens for this in the function

In this function added via addEventListener, the standard does not specify that this must refer to the target element. Although most browsers implement this, it is ultimately up to the browser implementation. When we need the target element, call event.currenttarget.

Level 2 DOM Event object

When called, JS will pass it an Event object. The following are the common properties of this Event object

  • CurrentTarget: (1) currentTarget: (2) currentTarget: (3)currentTarget: (3)currentTarget: (4)currentTarget: (4)currentTarget: (4)currentTarget: This property is different from the target property if the node is processing events during capturing and bubbling phases. In event listeners, use this property instead of this (4)stopPropagation(): preventDefault(5) : Prevents the browser from performing the default event-related action, as in the level 0 DOM where false is returned (6)clientX, clientY: the x-y coordinate of the mouse relative to the browser (7)screenX, screenY: the x-y coordinate of the mouse relative to the top left corner of the display

IE Event Model

1. Instead of passing Event objects to Event listeners, the Event objects are accessed through the Event property of the Window object.


2. Common properties of the IE Event object


  • Type: compatible with the DOM type attribute
  • SrcElement: DOM compatible target property
  • ClientX, clientY: Dom-compatible clientX, clientY properties
  • CancelBubble: Boolean, set to true
  • ReturnValue: Boolean, set to false and call preventDefault()

3. There is no addEventListener registered for the event listener, only attachEvent. 2 parameters, the same as the first two parameters of addEventListener, except that the event name is prefixed with on.

The IE event model has no capturing phases so calling attachEvent is equivalent to calling addEvetnListener with the third argument false:

document.getElementById("myTest").attachEvent(" function(){alert(1)});

The equivalent of

document.getElementById("myTest").addEventListener("click", function(){alert(1)}, false);

4. Functions registered with attachEvent will be called as global functions, rather than as methods on the document element where the event occurred.

That is, this refers to the window object, not the target element of the event.

Properties and methods under the event object:

Since each browser has different event objects, the main event object properties and methods are listed.

(1) bubble: indicates whether the event bubbles

(2) cancelable: indicates whether bubbling can be cancelled

CurrentTarget: the element being processed by the current event program, like this;

(4) Defaultprevent: false, preventDefualt is true;

Detail: information related to events (rolling events, etc.)

(6) eventPhase:

  • A value of 1 indicates that it is in the capture phase.
  • A value of 2 indicates that it is in the target phase,
  • Value of 3 means in the bubbling phase target | | srcElement: the target of the event trusted: for true is generated by the browser, to false is the developer to create (the DOM3)

(7) Type: indicates the event type

(8) View: window associated with the element, we may cross iframe;

(9) preventDefault();

(10) stopPropagation()

(11) stopImmediatePropagation() (DOM3) Prevents any events from running;

/ / stopImmediatePropagation block binding on other similar event callback event trigger element run Internet explorer of the event object is under the window, while the standard should be as a parameter, the first parameter of function;

IE event objects define different attributes from the standard, such as:

  • CancelBubble defaults to false and cancels event bubbling if it is true;
  • ReturnValue defaults to true; if false, cancel the default event;
  • SrcElement, which refers to target, is also srcElement in Firefox;

Event listener (including addEventListener and IE attacheEvent)

Older versions of IE (before IE 9) execute Javascript differently from almost all other browsers. In versions before IE 9, you need to use the attachEvent module, like this:

element.attachEvent(' function() { /* do stuff here*/ });Copy the code

In most other browsers (IE 9 and later), you can use addEventListener like this:

element.addEventListener('click', function() { /* do stuff here*/ }, false);

Inline Events (Inline Events, the HTML onclick=”” attribute and element.onclick)

On all javascript-enabled browsers, you can inline an event listener as shown in the following HTML code:

Example of inline events: <a ID ="testing" href="#" onclick="alert('did stuff inline');">Click me</a>Copy the code

While it’s certainly do-able and straightforward, most experienced developers try to avoid it.

Also, you can’t use closures or anonymous functions here (although the handler itself is an anonymous function), and your control is limited. Another way to do it is this

element.onclick = funtion () { /* do stuff here */ }Copy the code

In practice, this is equivalent to inline Javascript (the way you add HTML tag attributes above), but you can have more control and use anonymous functions, function expressions, or closures.

A major disadvantage of inline events is that, unlike the event listener mentioned above, you can only specify one inline event. Inline events transform attributes of meta elements, which means that when multiple inline events are specified, the previously specified inline events are overwritten.

Use the tag in the HTML code above for an example:

var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); }; 
element.onclick = function () { alert('did stuff #2'); };Copy the code

When you click on this element, you can only see “Did stuff #2”, because the second value overrides the onclick attribute specified in the first element, and also overrides the onclick attribute in the HTML.

Which is better…

The main issues are browser compatibility and necessity. Do you currently need to add more than one event to an element? Will it be needed in the future? Most of the time, you do. Therefore, it is necessary to use attachEvent and addEventListener instead of inline events.

JQuery and many other Javascript frameworks encapsulate common Models for handling DOM2 events for different browsers, so you can do cross-browser compatibility without having to worry about the legacy of Internet Explorer. The same code in jQuery is cross-browser compatible, just like this:

$(element).on('click'.function () { /* do stuff */ });Copy the code

Of course, don’t use a framework for such a thing. You can easily write a gadget that works with older browsers:

function addEvent(element, evnt, funct){
    if (element.attachEvent)
        return element.attachEvent('on' + evnt, funct);
    else
        return elemt.addEventListener(evnt, funct, false);
}

//example
addEvent(
    document.getElementById('myElement'),
    'click'.function () { aler('hi! '); });Copy the code

Event handler

Each event supported by an element can be specified using an HTML feature with the same name as the corresponding event handler. The value of this feature should be JavaScript code that can be executed.

Specifying event handlers in HTML has two drawbacks. One is jet lag. The other is that the HTML is tightly coupled to the JavaScript code (if you want to change the event handler, you have to change two things: the HTML code and the JavaScript code).

To specify an event handler using JavaScript, you must first get a reference to the object to operate on. Each element (including window and document) has its own event handler attributes, which are usually all lowercase, such as onclick. Setting the value of this property to a function specifies the event handler:

var btn = document.getElementByIdx_x("myBtn"); btn.onclick = function(){ alert("Clicked"); }

Event handlers specified using dom0-level methods are considered element methods. In other words, this in the program refers to the current element. Such as:

var btn = document.getElementByIdx_x("myBtn"); btn.onclick = function(){ alert("this.id"); }

To remove the DOM0-level event handler, simply do this:

btn.onclick = null; After setting the event handler to NULL, clicking the button will not take any action. If you specify an event handler using HTML, the value of the onclick property is a function that contains the code specified in the HTML property of the same name. Setting the corresponding property to NULL also removes event handlers specified in this manner.

Dom2-level event handlers (IE not supported) Dom2-level events define two methods for specifying and deleting event handlers:

AddEventListener () and removeEventListener (). var btn = document.getElementByIdx_x("myBtn"); btn.addEventListener("click",function(){alert("this.id"); },false);

The main benefit of adding event handlers using the DOM2-level approach is that you can add multiple event handlers. Such as:

var btn = document.getElementByIdx_x("myBtn"); btn.addEventListener("click",function(){alert("this.id"); },false); btn.addEventListener("click",function(){alert("hello world"); },false);

Delete the event application. Such as:

var btn = document.getElementByIdx_x("myBtn"); var handler = function(){ alert(this.id); }btn.addEventListener("click",handler,false); // omit other code btn.removeEventListener("click",handler,false); / / work!

Note: Anonymous functions cannot be deleted.

4, IE event handler

IE implements methods similar to those in the DOM: attachEvent() and detachEvent().

Such as:

var btn = document.getElementByIdx_x("myBtn"); btn.attachEvent("onclick",function(){alert("this.id"); });

Note: The first argument to attachEvent() is the same as the detachEvent() function used to delete the event handler.

The event type

DOM2 event Type (1) UI (user interface) event, which is triggered when a user interacts with an element on a page. (2) The mouse event is triggered when the user performs an operation on the page with the mouse. (3) Keyboard events, which are triggered when users perform operations on the page through the keyboard. (4) HTML events that are triggered when a browser window changes or a specific client/server interaction occurs. (5) Mutation events, which are triggered when the underlying DOM structure changes. (1) DOMActive: Indicates that the element has been activated by user action (mouse or keyboard). (2) DOMFocusIn: indicates that the element has been focused; (3) DOMFocousOut: indicates that the element has lost focus. Few browsers support these UI events, so we don’t recommend them. 3, mouse events (1) mouse events trigger sequence: mousedown- “mouseup-” click- “mousedown-” click- “dbclick. Var div = docment.getelementById (“myDiv”); EventUtil.addHandler(div,”click”,function(event){event = EventUtil.getEvent(event); alert(“Client coordinates:”+event.clientX+”,”+event.clientY); }); (3) Screen coordinate position

var div = document.getElementByIdx_x("myDiv"); EventUtil.addHandler(div,"click".function(event){event = EventUtil.getEvent(event); alert("Screen coordinates: " + event.screenX + ","+ event.screenY); }); });Copy the code

4. Keyboard events (DOM0-level events are supported) (1) Keyboard events include keyDown, keyPress, and keyUp. (2) keyCode. The keyCode attribute of the event object will contain a code corresponding to a specific key on the keyboard. Please refer to the corresponding key code table. 5, HTML events load, unload, abort, error, SELECT, change, submit, reset, resize, scroll, focus, blur. Most HTML events are related to window objects or form controls. 6. Changing events (omitted)