JavaScript event stream, event handler and event object summary, javascript events

Source: Internet
Author: User

JavaScript event stream, event handler and event object summary, javascript events

Interaction between JS and HTML is implemented through events. An event is a specific interaction moment in a document or browser window. You can use listeners (or handlers) to schedule events so that the corresponding code can be executed when an event occurs. This is called the observer mode in traditional software engineering and supports loose coupling between page behavior and page appearance. This article describes the basic knowledge about JS events.

I. event stream

The event stream describes the order in which events are received from the page.

Event bubbling

Events are received by the most specific elements (the node with the deepest nesting level in the document) at the beginning, and then gradually spread to a less specific node (document ). The following HTML page is used as an example. If you click the button on the page, the "click" event will be transmitted in the order of <button>, <body>,

Event capture

In contrast to the idea of event bubbling, the idea of event capturing is that the node should receive the event earlier, and the most specific node should receive the event at last. In the same example, after clicking the button on the page, the "click" event will be transmitted in the order of document,

DOM event stream

The "DOM2-level events" stipulate three phases: the event capture phase, the target phase, and the event bubble phase. First, event capture provides an opportunity to intercept events. Then, the actual target receives the event. The last stage is the bubble stage, where you can respond to events.

Take the previous button as an example. In the DOM event stream, during the capture phase, the "click" event is passed down from the document to the body element (note, the actual target button does not receive events in the capture phase ). In the target stage, the button element receives the "click" event. Finally, in the bubble stage, events are propagated back to the document.

Ii. event handling procedures

An event is an action performed by a user or a browser. A function that responds to an event is called an event handler or an event listener.

HTML event handler

Here, the HTML event handler refers to the event handler defined by the attribute in the HTML element. See the following code example. In this way, a specific event handler will create a function that encapsulates the element property value. The value of this is equal to the target element of the event. Using this method to specify the event handler has many disadvantages and is not recommended.

<button onclick="alert('HaHa~')">Btn-1</button><button onclick="alert('event.type')">Btn-2</button><button onclick="handler()">Btn-3</button><script type="text/javascript"> function handler() {  alert("Haha~"); }</script>

DOM0-level event handler

The traditional way to specify an event handler through JS is to assign a function to an event handler attribute. See the following code example. In this way, the specified event handler runs in the element scope, and this references the current element. The event handler added in this way will be processed in the bubbling phase of the event stream. To delete an event, set the onclick value to null.

Var btn = document. getElementById ("myBtn"); btn. onclick = function () {console. log ("this. id "); //" myBtn "}; // Delete the event handler btn. onclick = null;

DOM2-level event handler

DOM2-level events define two methods for specifying and deleting event handlers, addEventListener () and removeEventListener (). All DOM nodes contain these two methods. Both methods receive three parameters, including the event, processing function, and Boolean value to be processed. If the last Boolean value is true, the event handler is called in the capture phase. If the Boolean value is false, the handler is called in the bubble phase. Like the DOM0-level method, the event handler added here also runs in the scope of the element to which it is attached. The advantage of adding an event handler in the DOM2-level method is that multiple event handlers can be added. These event handlers are triggered in the order they are added. The following is a sample code:

Var btn = document. getElementById ("myBtn"); // Add. When a click event is triggered, output "myBtn" and then output "HaHa ~ "Btn. addEventListener ("click", function () {console. log (this. id) ;}, false); btn. addEventListener ("click", function () {console. log ("HaHa ~ ") ;}, False );

Events added through addEventListener () can only be deleted through removeEventListener. The parameters passed in during deletion must be consistent with those used during addition. This also means that the anonymous function added through addEventListener () cannot be deleted because the anonymous function passed during addition cannot be passed to removeEventListener (), even if an identical function is written during deletion, this function is only a new anonymous function. See the following code example:

Var btn = document. getElementById ("myBtn"); // The anonymous function btn cannot be deleted. addEventListener ("click", function () {console. log (this. id) ;}, false); btn. removeEventListener ("click", function () {console. log (this. id) ;}, false); // function handler () {console. log (this. id);} btn. addEventListener ("click", handler, false); btn. removeEventListener ("click", handler, false );

In most cases, the event handler is added to the bubbling stage of the event stream, which can be compatible with various browsers to the maximum extent. It is best to add the event handler to the capture phase only when the event is intercepted before it reaches the target. It is recommended that you do not register an event handler during the event capture phase if you do not need it.

IE event handler

IE implements two methods similar to DOM: attachEvent () and deleteEvent (). The two methods receive two parameters: the name of the event handler and the event handler. Note that the first parameter is the event handler name rather than the event name. That is to say, when registering the event handler, you should input "onclick" instead of "click ", here is a little different from the DOM method. In addition, the event handler registered by these two methods runs in the global scope rather than the element scope, and the value of this points to window. Note that you can add multiple Event Handlers through the attachEvent () method, but their execution sequence is not in the order they are added, but completely opposite, different from DOM methods. I suddenly think that IE is really very anti-human ~~~ The following is a sample code:

Var btn = document. getElementById ("myBtn"); function handler1 (){//...} function handler2 (){//...} // Add. When the click event is triggered, execute handler2 and then execute handler1btn. attachEvent ("onclick", handler1); btn. attachEvent ("onclick", handler2); // Delete btn. deleteEvent ("onclick", handler1); btn. deleteEvent ("onclick", handler2 );

Iii. event object

When an event on the DOM is triggered, an event object is generated. This object contains all event-related information, includes the elements that cause the event, the event type, and other information related to the specific event.

Event object in DOM

A dom-compatible browser will pass an event object into the event handler. no matter whether the specified event handler uses the DOM0 or DOM2 method, the event object will be passed in. The event object exists only during the execution of the event processing program. Once the event processing program is executed, the event object will be destroyed. The following is a sample code:

var btn = document.getElementById("myBtn");btn.onclick = function(event) { console.log(event.type); // "click"}btn.addEventListener("click", function(event) { console.log(event.type);}, false);

The event object contains the attributes and methods related to the specific events that you create. The types of events that are triggered are different, and the available attribute methods are also different. However, all events have the following attributes or methods:

  • Bubbles: Boolean value, indicating whether the event is bubbling
  • Cancelable: Boolean value, indicating whether the default event behavior can be canceled
  • CurrentTarget: element of the event handler currently processing the event
  • DefaultPrevented: Boolean value, indicating whether the preventDefault () method has been called
  • Detail: integer, event-related details
  • EventPhase: an integer. It indicates the stage of the event handler. 1 indicates the capture stage, 2 indicates the target stage, and 3 indicates the bubble stage.
  • PreventDefault (): function, used to cancel the default event action. This method can be called if cancelable is set to true.
  • StopImmediatePropagation (): function to cancel further event capture or bubbling and prevent any event handler from being called.
  • StopPropagation (): function to cancel further event capture or bubbling. This method can be called when the bubbles is true.
  • Target: element, event target
  • Trusted: Boolean value. If it is true, the event is generated by the browser. Otherwise, the event is created through JS.
  • Type: string, the type of the event to be triggered
  • View: the abstract view associated with the event. It is equivalent to the window object in which the event occurs.

The following code example demonstrates the usage of some of the above attributes and helps us further understand the event stream. Suppose there is a button "myBtn" in the page ". When you click the button, both this and currentTarget are equal to the body element, because the event handler is registered on the body element. The value of target is equal to the button element because it is the real target of the click event. Because the event handler is not registered on the button, the result "click" event is only processed after it is bubbling to document. body.

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

In the following code, the stopPropagation () method cancels further event capture or bubbling. When I click the button, the event handler triggered by the event bubbling mechanism and the click event handler on the body element will output "From Bth ..." And "From Body ...". Now, when an event is triggered on the button element, it is blocked from spreading in the DOM layer. Therefore, the event handler on the body is not triggered.

Var btn = document. getElementById ("myBtn"); btn. onclick = function (event) {console. log ("From Bth... "); event. stopPropagation (); // stop event propagation}; document. body. onclick = function () {console. log ("From Body... ");};

Event object in IE

In IE, when you use the DOM0 method to add an event handler, the event object exists as an attribute of the window object. If it is added using the attachEvent () method, the event object is passed into the event processing function as a parameter. The following is a sample code:

var btn = document.getElementById("myBtn");btn.onclick = function() { var event = window.event; console.log(event.type); // "click"};btn.attachEvent("onclick", function(event) { console.log(event.type); // "click"});

The event object of IE also contains the attributes and methods related to the events created for it. These attributes and methods are also different because of the different event types. However, all event objects contain the following attributes:

  • CancelBubble: Boolean value, readable and writable. The default value is false. When it is set to true, the event bubble is canceled.
  • ReturnValue: Boolean value, readable and writable. The default value is true. Set it to false to cancel the default event behavior.
  • SrcElment: element, the target element of the event, which is the same as the target attribute in the DOM.
  • Type: String, event type

In IE, the scope of the event handler is determined by specifying it. The value of this is not necessarily the target element of the event. Therefore, using the srcElement property is more secure. See the following code example. In the first method, the value of this is the target element, while in the second method, the event handler in this method is executed in the global scope, therefore, the value of this is window.

var btn = document.getElementById("myBtn");btn.onclick = function() { console.log(window.event.srcElement === this); // true}btn.attachEvent("onclick", function(event) { console.log(event.srcElement === this); // false});

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.