The interaction between JS and HTML is achieved through events. An event is some specific interaction moment that occurs in a document or browser window. An event can be scheduled using (or a handler) so that the corresponding code is executed when the event occurs. This is called observer mode in traditional software engineering, supporting a loose coupling between the behavior of the page and the appearance of the page. This article will introduce the basics related to JS events.
1. Event flow
Event streams describe the order in which events are received from the page.
Event bubbles
The event starts by the most specific element (the node with the deepest nesting level in the document) and then propagates up step by step to the less specific node (document). As an example, if you click the button in the page, the "click" event will be propagated in the order of < button>, < body>, < html>, and document. In other words, event bubbles refer to the event that starts from the element that triggers the event at the bottom layer and travels up along the DOM tree until the document object.
<html> <head> <title>Test</title> </head> <body> <button >A Btn</button> </body> </html>
Event Capture
Contrary to the idea of bubbling events, the idea of event capture is that less specific nodes should receive events earlier, and the most specific nodes should receive events at the end. The same is true for the example above. After clicking the button in the page, the "click" event will be propagated in the order of document, <html>, <body>, and < button>. In other words, event capture refers to the event being propagated down the DOM tree from the document object until the actual target element of the event.
DOM event stream
The events specified in the "DOM2 level event" include three stages: the event capture stage, the target stage and the event bubble stage. The first thing that happens is event capture, which provides an opportunity to intercept events. Then the actual target receives the event. The last stage is the bubble phase, where events can be responded to.
Take the previous click button as an example. In the DOM event stream, in the capture stage, the "click" event is passed down to the body element from the document (note that the actual target button will not receive the event in the capture stage). During the target stage, the button element receives a "click" event. Finally, in the bubbling phase, the event is propagated back to the document.
2. Event handler
An event is an action performed by the user or browser itself, and the function that responds to a certain event is called an event handler or event.
HTML event handler
The HTML event handler here refers to an event handler directly defined in an HTML element through attributes. Please see the code example below. This is the event handler that creates a function that encapsulates the element attribute value, and this value is equal to the target element of the event. This method specifies event handlers with many disadvantages and is not recommended.
<button onclick="alert('HaHa~')">Btn-1</button> <button onclick="alert('')">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. Please see the code example below. The event handler specified in this way is run in the scope of the element, and this refers to the current element. The event handler added in this way will be processed during the bubbling phase of the event stream. To delete the event, just turn the value of onclick to empty.
var btn = ("myBtn"); = function() { (""); // "myBtn" }; // Delete event handler = null;
DOM2 level event handler
"DOM2 level event" defines two methods for specifying and deleting event handlers, addEventListener() and removeEventListener(). All DOM nodes contain these two methods. Both methods receive 3 parameters, the event to be processed, the processing function, and the boolean value. When the last boolean value is true, the event handler is called in the capture stage, and when false, the handler is called in the bubble stage. Like the DOM0-level method, the event handler added here also runs in the scope of the elements it attaches to. The advantage of adding event handlers at the DOM2 level method is that multiple event handlers can be added. These event handlers are fired in the order in which they are added. Here is a code example:
var btn = ("myBtn"); // Add, when triggering the click event, first output "myBtn" and then output "HaHa~"("click", function() { (); }, false); ("click", function() { ("HaHa~"); }, false);
Events added through addEventListener() can only be deleted by removeEventListener(). The parameters passed in when deleting should be consistent with the parameters used when adding. This also means that the anonymous function added through addEventListener() will not be deleted, because the anonymous function passed when adding cannot be passed to removeEventListener(). Even if an exact same function is written during the deletion, this function is just a new anonymous function at this time. Please see the following code example:
var btn = ("myBtn"); // Cannot delete anonymous functions("click", function() { (); }, false); ("click", function() { (); }, false); // Correct ways to add and deletefunction handler() { (); } ("click", handler, false); ("click", handler, false);
In most cases, event handlers are added to the bubbling phase of the event stream, which can maximize compatibility with various browsers. It is best to add the event handler to the capture phase only if it needs to be intercepted before it reaches the target. The advice given in JS advanced programming is that if it is not particularly necessary, it is not recommended to register event handlers during the event capture phase.
IE event handler
IE implements two similar methods as in DOM: attachEvent() and deleteEvent(). These two methods receive two parameters, the event handler name and the event handler. Note that the first parameter is the event handler name instead of the event name, which means that when registering the handler for click events, "onclick" should be passed in instead of "click". This is somewhat 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. Another thing to be careful. Multiple event handlers can be added through the attachEvent() method, but their execution order is not in the order in which they are added, but is completely opposite, which is completely different from the DOM method. Here is a code example:
var btn = ("myBtn"); function handler1() { // ... } function handler2() { // ... } // Add, when triggering the click event, first execute handler2 and then execute handler1("onclick", handler1); ("onclick", handler2); // delete("onclick", handler1); ("onclick", handler2);
III. Event Object
When an event on the DOM is triggered, an event object event is generated, which contains all the information related to the event, including the elements that caused the event, the type of the event, and other information related to a specific event.
Event Objects in DOM
A DOM-compatible browser will pass an event object into the event handler. No matter whether the DOM0 or DOM2 method is used when specifying the event handler, the event object will be passed. The event object will only exist during the execution of the event handler. Once the event handler is executed, the event object will be destroyed. Here is a code example:
var btn = ("myBtn"); = function(event) { (); // "click" } ("click", function(event) { (); }, false);
The event object contains properties and methods related to the specific event that created it. The triggered event types are different, and the available attribute methods are also different. However, all events will have the following properties or methods:
- bubbles: boolean value, indicating whether the event is bubbled
- cancelable: Boolean value indicating whether the default behavior of the event can be canceled
- currentTarget: element, which element the event handler is currently processing the event
- defaultPrevented: Boolean value, indicating whether the preventDefault() method has been called
- detail: integer, event-related details
- eventPhase: integer, the stage where the event handler is called, 1 represents the capture stage, 2 represents the target stage, and 3 represents the bubble stage
- preventDefault(): function, cancel the default behavior of events, this method can be called when cancelable is true
- stopImmediatePropagation(): function, cancels further capture or bubbling of events, while preventing any event handler from being called
- stopPropagation(): function, cancel further capture or bubbles of events, this method can be called when bubbles are true
- target: element, the target of event
- trusted: Boolean value, when true, it means that the event is generated by the browser, otherwise it means that the event is created through JS
- type: string, triggered event type
- view: an abstract view associated with an event, equivalent to a window object where the event occurred
The following code example shows the usage of some of the above attributes, which can also help us further understand event flow. Suppose there is a button "myBtn" in the page. When a button is clicked, both this and currentTarget are equal to the body element, because the event handler is registered on the body element. The value of the target is equal to the button element, because it is the real target of the click event. Since there is no registered event handler on the button, the "click" event bubbled there before it was processed.
= function(event) { ( === ); // true (this === ); // true ( === ("myBtn")); // true };
Let’s take another example. In the following code, the stopPropagation() method cancels further capture or bubbles of events. When I click the button, the click event handler on the button and body element should have been triggered due to the event bubble mechanism, and the output "From Bth..." and "From Body..." are output. Now the click event is blocked from continuing to propagate in the DOM level after it is fired on the button element, so the event handler on the body will not be fired.
var btn = ("myBtn"); = function(event) { ("From Bth ..."); (); // Stop event propagation}; = function() { ("From Body ..."); };
Event Objects in IE
In IE, when adding an event handler using the DOM0 method, the event object exists as a property of the window object. If it is added through the attachEvent() method, the event object is passed into the event handler function as a parameter. Here is a code example:
var btn = ("myBtn"); = function() { var event = ; (); // "click" }; ("onclick", function(event) { (); // "click" });
The IE event object also contains attributes and methods related to the event that created it, and these attributes and methods will also vary depending on the event type. But all event objects will contain the following properties:
- cancelBubble: Boolean value, readable and writable, default to false. Cancel event bubbles when setting it to true
- returnValue: Boolean value, readable and writable, default to true. Cancel the default behavior of events when setting it to false
- srcElment: element, the target element of the event, the same as the target attribute in the DOM
- type: string, event type
In IE, the scope of the event handler is determined according to the way it is specified, and the value of this does not necessarily point to the target element of the event. Therefore, using the srcElement property is more secure. Please see the following code example. In the first way, the value of this is the target element, while in the second way, the event handler in this way mentioned earlier is executed in the global scope, so the value of this is window.
var btn = ("myBtn"); = function() { ( === this); // true } ("onclick", function(event) { ( === this); // false });
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!