Reading notes of JavaScript advanced programming (9)

Time:2021-7-14

Recently, I’ve been so busy that I’ve turned a beautiful girl into a national treasure. Finally, it’s over. What I’m left with is still the charm (black eye circle)~
If you don’t have much to say, eat first^_^


Chapter 13 events

The interaction between JavaScript and html is realized by events.
Events are specific interaction moments that occur in a document or browser window.

Event flow – event bubbling

IE’s event flow is called event bubble, 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 upward to the less specific node (document).
For example, for a page with only one < div > element in the < body > tag, if you click < div > in the page, the click event will be propagated in the following order:
(1) <div>
(2) <body>
(3) <html>
(4) document
In other words, the click event first occurs on the < div > element, which is the element we click.
Then, the click event propagates up the DOM tree and occurs at each level node until it propagates to the document object.
The figure below perfectly shows the bubble process of time.
Reading notes of JavaScript advanced programming (9)

Event flow – event capture

The idea of event capture is that the less specific node should receive the event earlier, while the most specific node should receive the event last.
The purpose of event capture is to capture an event before it reaches its intended target. In the bubble example above, clicking the < div > element triggers the click event in the following order
(1) document
(2) <html>
(3) <body>
(4) <div>
In the process of event capture, the document object first receives the click event, and then the event propagates up the DOM tree to the actual purpose of the event, that is, the < div > element. As shown in the figure below:
Reading notes of JavaScript advanced programming (9)

Event flow – dom event flow

The event flow of “dom2 level event” includes three stages: event capture stage, target stage and event bubbling stage.
The first is event capture, which provides an opportunity to intercept events. Then the actual target receives the event. The last stage is the bubbling stage, where you can respond to events.
Reading notes of JavaScript advanced programming (9)

Event handler

An event is an action performed by the user or the browser itself. Such as click, load, and mouseover are the names of the events. The function that responds to an event is called an event handler (or event listener).
The name of the event handler starts with “on”, so the event handler of the click event is onclick, and the event handler of the load event is onload. There are several ways to specify a handler for an event.

Event handler — HTML event handler

When the code in the event handler executes, it has access to any code in the global scope.
This specifies that the event handler has some originality. First, this creates a function that encapsulates the attribute value of an element. In this function, there is a local variable event, which is the event object
< input type = button "value = click me" onclick = alert (event. Type) "> // output" click "
Through the event variable, you can directly access the event object. You don’t need to define it yourself or read it from the parameter list of the function. Inside this function, the value of this is equal to the target element of the event
< input type = "button" value = "click me" onclick = "alert (event. Type)" > // output "click me"

Event handler — dom0 level event handler

Each element (including window and document) has its own time handler properties. These properties are usually all lowercase, such as onclick. Setting the value of this property as a function can specify the event handler.

var btn = document.getElementById("myBtn");
btn.onclick = function(){
    alert(this.id);    //"myBtn"
}
btn.onclick = null;      // Delete event handler
Event handler — dom2 level event handler

“Dom2 level event” defines two methods to handle the operations of specifying and deleting event handlers: addeventlistener() and removeeventlistener().
All DOM nodes contain these two methods, and they all take three parameters: the name of the event to be processed, the function as the event handler, and a Boolean value.
Finally, if the Boolean parameter is true, it means that the event handler is called in the capture phase; If false, the event handler is called during the bubbling phase.

var btn = document.getElmentById("myBtn");
btn.addEventListener("click",function(){
    alert(this.id);
},false);   // This event is triggered during the bubbling phase
btn.addEventListener("click",function(){
    alert("Hello world!");
},false);

The main advantage of using the dom2 level method to add event handlers is that you can add multiple event handlers.
The above example adds two event handlers to the button, which are triggered in the order in which they are added, so the ID of the element is displayed first, followed by “Hello world!” News.
The event handler added by addeventlistener() can only be removed by removeeventlistener(); The parameters passed in when removing are the same as those used when adding the handler. This also means that anonymous functions added through addeventlistener() cannot be removed. Just like the example above.

Event handler — ie event handler

Ie implements two methods similar to DOM: attachevent() and detachevent(). The two methods take the same two parameters: the event handler name and the event handler function.
To add an event handler for the button using attachevent(), use the following code.

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

Note that the first parameter of attachevent () is “onclick”, not “click” in the addeventlistener () method of DOM.

The main difference between using attachevent() in IE and using dom0 level methods is the scope of the event handler. In the case of dom0 level method, the event handler will run in the scope of its element; In the case of using the attachevent() method, the event handler will run in the global scope, following the assumption that this is equal to window.
var btn = document.getElementById(“myBtn”);
btn.attachEvent(“onclick”, function(){

alert(this === window);     //true

});
It’s important to keep this distinction in mind when writing cross browser code.
Like addeventlistener(), the attachevent() method can also be used to add multiple event handlers to an element.
Unlike DOM methods, these event handlers are not executed in the order in which they are added, but are triggered in the reverse order.
Events added using attachevent() can be removed by detachevent(), provided the same parameters are provided. Like the DOM method, this means that the added anonymous function cannot be removed.

Event object — event object in DOM

DOM compatible browsers pass an event object into the event handler. No matter what method (dom0 level or dom2 level) is used to specify the event handler, an event object is passed in.

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

An event object contains properties and methods related to the specific event in which it was created. The types of events triggered are different, and the available properties and methods are also different. All events will have members listed in the following table.
Reading notes of JavaScript advanced programming (9)
Reading notes of JavaScript advanced programming (9)

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

var btn = document.getElementById("myBtn");
btn.onclick = function(event){
    alert(event.currentTarget === this);     //true
    alert(event.target === this);       //true
}

To prevent the default behavior for a particular event, use the preventdefault () method.
For example, the default behavior of a link is to navigate to the URL specified by the URL attribute when it is clicked. If you want to prevent the default behavior of link navigation, you can cancel it through the onclick event handler of the link.

var link = document.getElementById("myLink");
link.onclick = function(event) {
    event.preventDefault();
}

Only events whose cancellable property is set to true can use preventdefault() to cancel their default behavior.
In addition, the stoppropagation () method is used to immediately stop the propagation of events in the DOM hierarchy, that is, to cancel further event capture or bubbling.
For example, a time handler added directly to a button can call stoppropagation () to avoid triggering the event handler registered on document. Body.

var btn = document.getElementById("myBtn");
btn.onclick = function(event){
    alert("Clicked");
    event.stopPropagation();
};
document.body.onclick = function(event) {
    alert("body clicked");
}

For the above example, if stoppropagation () is not called, two warning boxes will appear when the button is clicked. However, since the click event will not propagate to document. Body at all, the onclick event handler registered on this element will not be triggered.

The eventphase property of the event object can be used to determine which stage of the event flow the event is currently in.
If the event processing is called in the capture phase, then eventphase is equal to 1;
If the event handler is on the target object, then eventphase is equal to 2;
If it is an event handler called in the bubbling phase, eventphase is equal to 3
It should be noted here that although “in target” occurs in the bubbling phase, eventphase is still equal to 2.

var btn = document.getElementById("myBtn");
btn.onclick = function(event){
    alert(event.eventPhase);   //2
};

document.body.addEventListener("click", function(event){
    alert(event.eventPhase);   //1
}, true);

document.body.onclick = function(event) {
    alert(event.eventPhase);   //3
};

When you click the button in this example, the first event handler to be executed is the one added to the document. Body, which is triggered in the capture phase. As a result, a warning box will pop up, showing 1 indicating eventphase. Next, the event handler registered on the button is triggered with an eventphase value of 2. The last event handler to be triggered is the one added to the document. Body that is executed in the bubbling phase, showing that the value of eventphase is 3. When eventphase is equal to 2, this. Target and currenttarget are always equal.
The event object exists only during the execution of the event handler; Once the event handler is executed, the event object is destroyed.

Event type

There are many types of events that can occur in a web browser.

  • UI events are triggered when users interact with elements on the page;
  • Focus event, which is triggered when an element gains or loses focus;
  • Mouse event, triggered when using mouse wheel;
  • Text event, which is triggered when text is input into the document;
  • Keyboard event, which is triggered when the user performs the operation on the page through the keyboard;
  • Composite event, which is triggered when characters are input for ime;
  • Change event, which is triggered when the underlying DOM structure changes.
UI events

UI events refer to those events that are not necessarily related to user actions.

  • Load: it is triggered on the window when the page is fully loaded, on the frameset when all frames are loaded, on the < img > element when the image is loaded, or on the < Object > element when the embedded content is loaded.
  • Unload: it is triggered on the window when the page is completely unloaded, on the frame when all frames are unloaded, or on the < Object > element when the embedded content is unloaded.
  • Error: trigger on window when JavaScript error occurs, on < img > element when image cannot be loaded, on < Object > element when embedded content cannot be loaded, or on frameset when one or more frames cannot be loaded.
  • Select: trigger on the window or frame when the size of the window or frame changes.
  • Reset: trigger on the window or frame when the size of the window or frame changes.
  • Scroll: triggered when the user scrolls the contents of an element with a scroll bar< The body > element contains the scroll bar of the loaded page.
focal event

The focus event is triggered when the page gains or loses focus. By using these events and cooperating with the document. Hasfocus () method and the document. Activeelement attribute, we can know the user’s whereabouts on the page.

  • Blur: triggers when an element loses focus. This event doesn’t bubble. All browsers support it.
  • Focus: triggered when the element gets the focus. This event doesn’t bubble. All browsers support it.
Mouse and wheel events
  • Click: triggered when the user clicks the main mouse button or presses enter.
  • Dblclick: triggered when the user double clicks the main mouse button.
  • MouseDown: triggered when the user presses any mouse button. This event cannot be triggered from the keyboard.
  • Mouseenter: triggered when the mouse cursor first moves from outside the element to within the range of the element. This event doesn’t bubble and doesn’t trigger when the cursor moves over a descendant element.
  • Mouseleave: triggered when the mouse cursor over the element moves out of the range of the element. This event doesn’t bubble and doesn’t trigger when the cursor moves over a descendant element.
  • MouseMove: when the mouse pointer moves inside the element, try to trigger repeatedly. This event cannot be triggered from the keyboard.
  • Mouseout: triggered when the mouse pointer is over one element and the user moves it into another. Another element moved in may be outside the previous element, or it may be a child element of this element.
  • Mouseover: triggered when the mouse pointer is outside one element and the user moves it into the boundary of another element for the first time.
  • Mouseup: triggered when the user releases the mouse button.

All elements on the page support mouse events.
Except mouseenter and mouseleave, all mouse events will bubble and can be cancelled. Canceling mouse events will affect the default behavior of the browser.

Only when MouseDown and mouseup events are triggered successively on the same element, the click event will be triggered; If either MouseDown or mouseup is cancelled, the click event is not triggered.
Similarly, the dblclick event is triggered only once if the click event is triggered twice.
The sequence of these four events is always as follows:
(1)mousedown
(2)mouseup
(3)click
(4)mousedown
(5)mouseup
(6)click
(7)dblclick
Obviously, both click and dblclick events depend on the triggering of other antecedent events; MouseDown and mouseup are not affected by other events.

1. Coordinate position of customer area
Mouse events occur at specific locations in the browser’s view. This location information is stored in the clientx and clienty properties of the event object.
Their values represent the horizontal and vertical coordinates of the mouse pointer in the viewport at the time of the event.
2. Page coordinate position
Through the coordinates of client area, we can know where the mouse happened in the view, and page coordinates can tell you where the event happened in the page through the pagex and pagey attributes of the event object. In other words, these two properties represent the position of the mouse cursor in the page, so the coordinates are calculated from the page itself rather than the left and top edges of the viewport.
When the page is not scrolling, the values of pagex and pagey are equal to the values of clientx and clienty.
3. Screen coordinate position
When the mouse event occurs, there will be not only a position relative to the browser window, but also a position relative to the whole computer screen. Through the screen X and screen y attributes, we can determine the coordinate information of the mouse pointer relative to the whole screen when the mouse event occurs.
4. Mouse button
The click event is triggered only when the main mouse button is clicked, so it is not necessary to detect the button information. However, for MouseDown and mouseup events, there is a button attribute in their event object, which indicates the pressed or released button.
The button attribute of DOM may have the following three values: 0 represents the main mouse button, 1 represents the middle mouse button (mouse wheel button), and 2 represents the secondary mouse button.
4. Touch device
IOS and Android devices are very special because they don’t have a mouse.

  • Dblclick event is not supported. Double click the browser window will enlarge the screen, and there is no way to change the behavior.
  • Tapping the clickable element triggers the MouseMove event. If this operation will cause content changes, no other events will occur; If the screen does not change as a result, the MouseDown, mouseup, and click events occur in turn. Tapping a non clickable element does not trigger any events.
  • The MouseMove event also triggers mouseover and mouseout events.
  • Mousewheel and scroll events are triggered when two fingers are placed on the screen and the page scrolls as the fingers move.
Keyboard and text events

There are three keyboard events, briefly described below.

  • Keydown: this event is triggered when the user presses any key on the keyboard, and if it is held down, this event will be triggered repeatedly.
  • Keypress: it is triggered when the user presses the character key on the keyboard, and if it is held down, this event will be triggered repeatedly.
  • Keyup: triggered when the user releases the key on the keyboard.
Touch and gesture events – touch events

Touch start: triggered when the finger touches the screen; Even if a finger is already on the screen, it will trigger.
Touch move: the program is triggered continuously when it slides on the screen. During this event, calling preventdefault() prevents scrolling.
Touch end: triggered when the finger moves away from the screen.
Touch cancel: triggered when the system stops tracking the touch.
All of these events will bubble and be cancelled.

Touch and gesture events – gesture events

Safari in IOS 2.0 also introduces a set of gesture events. Gestures are generated when two fingers touch the screen. Gestures usually change the size of the display item or rotate the display item.

  • Gesturestart: triggered when one finger has been pressed on the screen and the other finger touches the screen.
  • Gesturechange: triggered when the position of any finger touching the screen changes.
  • Gestureend: triggered when any finger moves away from the top of the screen.

Memory and performance — event delegation
The solution to the problem of “too many event handlers” is event delegation. Event delegation takes advantage of event bubbling. It can manage all events of a certain type by specifying only one event handler. For example, the click event bubbles all the way to the document level.
If possible, consider adding an event handler for the document object to handle a specific type of event that occurs on the page. The advantages are as follows:

  • The document object is accessible quickly, and event handlers can be added to it at any point in the page life cycle (without waiting for the domcontentloaded or load event). In other words, as long as the clickable elements are presented on the page, they immediately have the appropriate functionality.
  • It takes less time to set up event handlers on the page. Adding just one event handler requires fewer DOM references and takes less time.
  • The whole page takes up less memory space, which can improve the overall performance.

The most suitable events for event delegation include click, MouseDown, mouseup, Keydown, Keyup and keypress. Although mouseover and mouseout events also bubble, it is not easy to handle them properly, and it is often necessary to calculate the position of elements( The mouseout event is triggered when the mouse moves from an element to its child node, or when the mouse moves out of the element.)

Summary
Events are the main form of linking JavaScript with web pages“ The DOM Level 3 event specification and HTML5 define most common events. Even if some specifications define basic events, many browsers still implement their own special events outside of the specifications, so as to provide developers with more means to master user interaction.

  • When using events, you need to consider the following memory and performance issues
  • It is necessary to limit the number of event handlers in a page. Too many event handlers will occupy a lot of memory and make users feel that the page is not responsive enough.
  • Event delegation technology based on event bubbling mechanism can effectively reduce the number of event handlers.
  • Set up to remove all event handlers from the page before the browser unloads the page.

Event is one of the most important topics in JavaScript. It is very important to deeply understand the working mechanism of events and their impact on performance.

Well, that’s about it~