When interacting with a browser, the browser triggers various events. For example, when a webpage is opened and the webpage is loaded by the browser, a load event is triggered. When we click...
When interacting with a browser, the browser triggers various events. For example, when a webpage is opened and the webpage is loaded by the browser, a load event is triggered. When we click a "place" in the webpage ", the browser will trigger a click event in that "place.
In this way, we can write JavaScript to implement some function extensions by listening to an event. For example, to listen to the load event and display the welcome information, the welcome information will be displayed after the browser loads a webpage.
The following describes the events.
Basic Event operation listening event
The browser will trigger the corresponding event based on some operations. If we need to process an event, we need to listen to this event. The following methods are used to listen to events:
HTML inline attributes (avoid use)
In the HTML element, directly fill in the event-related attributes. The property value is JavaScript code, and the content of the attribute value can be executed when the event is triggered.
For example:
Click this button
The onclick attribute indicates that the click is triggered. The content of the attribute value (JavaScript code) is executed when the HTML node is clicked.
Obviously, using this method, JavaScript code is coupled with HTML code, which is not easy to maintain and develop. Therefore, this method should be avoided unless necessary (for example, statistical link click data.
DOM property binding
You can also directly set the DOM attribute to specify the corresponding handler for an event. This method is relatively simple:
Element. onclick = function (event) {alert ('You clicked this button ');};
The above code listens to the click Event of the element node. It is easy to understand and has good compatibility. However, there are also defects, because the corresponding attribute is assigned directly. If you bind a callback function to the element again in the subsequent code, the content of the previous callback function will be overwritten.
Although multiple bindings can be implemented using some methods, the following standard event listening functions are recommended.
Use event listening Functions
The standard event listening functions are as follows:
element.addEventListener(
,
,
);
Add an event listener to the object of element. When an event occurs This callback function. As This parameter indicates whether the event listener listens during the capture phase (set to true) or during the bubble phase (set to false ). We will explain the capture and bubble operations below.
Use the standard event listening function to rewrite the above example:
Var btn = document. getElementsByTagName ('click'); btn [0]. addEventListener ('click', function () {alert ('You clicked this button ');}, false );
It is best to define an id or class attribute for the HTML structure to facilitate selection. It is only used for demonstration here.
Demo:
Remove event listening
When we bind an event to an element, the callback function bound to the event is executed every time this event is triggered. If we want to unbind, we need to use the removeEventListener method:
element.removeEventListener(
,
,
);
It should be noted that the callback function during event binding cannot be an anonymous function and must be a declared function, because the callback function must be referenced when the event is unbound, to disconnect the binding. For example:
var fun = function() { // function logic};element.addEventListener('click', fun, false);element.removeEventListener('click', fun, false);
Demo:
Event triggering Process
We have a general understanding of what an event is and how to listen for and execute some operations, but we are not familiar with the entire process of event triggering.
Is the event trigger process, borrow the W3C Image
Capture Phase)
When some operations (such as clicking and moving the mouse) occur on a node in the DOM tree, an event is triggered. This event is sent from the Window and continues to pass through the lower-level node until the target node. The process before reaching the target node is the Capture Phase (Capture Phase ).
This event is triggered for all nodes that pass through. The task in the capture phase is to establish the event transfer route so that the subsequent bubble phase can follow this route to return the Window.
To listen to an event triggered during the capture phase, you must pass the third parameter true in the event listening function.
element.addEventListener(
,
, true);
However, in general use, we often pass false, which will be explained later.
Target Phase)
When the event runs and runs to the target node where the event is triggered, the event is triggered on the target node, which is the target stage.
Note that the event-triggered target is always the underlying node. For example, if you click a piece of text, you think that the target node of your event is on p, but it is actually triggered on
. For example:
In the Demo, I click an event to display the tag name of the target node. When you click the bold font, the target node of the event is the underlying node.Node.
Bubbling Phase)When the event reaches the target node, it will return along the original path. This process is called the bubble stage because bubbles floated from the bottom to the top.
In actual use, you do not need to accurately bind the event listening function to the underlying node. For example, in the above example, you want
The callback function when you bind a click.
All the following subnodes are bound to the click event.
This node can be bound. Because the click event of its subnode will bubble up and occur in
Above.
For these three stages, wilsonpage made a great Demo. You can see:
Why not use the third parameter true?After introducing the trigger phase of the above three events, let's take a look at this problem.
All the articles about events will say that when the addEventListener function is used to listen to events, the third parameter is set to false. In this way, only events in the bubble phase will be monitored during event monitoring.
This is because the IE browser does not support listening to events in the capture phase. It is set for unification. After all, the shares of the IE browser cannot be ignored.
There are some other differences between the IE browser and the standard in terms of events, which we will focus on later.
Use Event Delegate to improve performanceBecause the event has a bubbling mechanism, all the subnode events will run back along the parent node, so we can monitor the parent node to implement the function of listening to the subnode, which is the event proxy.
Event proxy has two main advantages:
Reduces event binding and improves performance. You need to bind a bunch of child nodes before, but now you only need to bind a parent node. Reduces the number of event listening functions.
The dynamically changed DOM structure can still be monitored. When a DOM is dynamically created, there will be no event listening, unless you re-execute the event listening function, and using event listening does not have to worry about this issue.
Let's look at an example:
In the above example, for ease of use, I use jQuery to implement normal event binding and event proxy. My goal is to listen to all click events on the link. ul1 is a conventional event binding method. jQuery will loop through every. ul> a structure and bind the event listening function .. Ul2 is the method for event listening, jQuery is only. ul2 structure binding event listening function, because. there may be many irrelevant nodes under ul2 that will trigger the click event, so I passed the second parameter in the on function, indicating to only listen to the events of a subnode.
They can all work normally, but when I dynamically create a new DOM structure, the first ul problem occurs, although the new structure is still. ul1> a, but no event is bound, so the callback function cannot be executed. The second ul works very well, because clicking on the newly created DOM will bubble up its events to the parent node for processing.
If you use the native method to implement event proxy, you must filter non-target nodes by id, class, or tagname. For example:
Element. addEventListener ('click', function (event) {// determine whether it is a node if (event.tar get. tagName = 'A') {// some interactive operations of A }}, false );StopPropagation)All things have the opposite. Although the event bubble stage looks good, there will also be unsuitable places. Because event listening is complicated, you may want to only listen for events that occur on specific nodes. In this case, stop the event bubble.
To stop event bubbling, you must use the stopPropagation method of the event object. The Code is as follows:
element.addEventListener('click', function(event) { event.stopPropagation();}, false);In the callback function of Event listening, a parameter is passed, which is the Event object. The Event bubble can be stopped by calling the stopPropagation Method on this object. For example, an application that stops event bubbling:
JS Bin
In the above example, there is a pop-up layer where we can perform any operations, such as click. When we want to turn off this pop-up layer, click any structure outside the pop-up layer to turn it off. It first monitors click events on the document node. All click events are hidden from the pop-up layer. Similarly, the click operation on the pop-up layer also hides the pop-up layer. Then we use the stop event bubbling function on the pop-up layer to cut off the bubble route for clicking the event to return the document, so that the operations on the pop-up layer will not be listened to by the event processing function of the document.