laitimes

Section 55 Event Event - Javascript for Web Front-End Development - Zero Point Programmer - Wang Wei

author:Zero point programmer

This content is the courseware of "Javascript Video for Web Front-end Development", please cooperate with the "Javascript" video course of Master Brother.

Javascript's interaction with HTML is achieved through events, which employ an asynchronous event-driven programming model;

Event:

This is some specific moment of interaction that occurs in a document or browser window; you can use a listener (or handler) to schedule an event so that the corresponding code is executed when the event occurs;

This approach is known in traditional software engineering as the observer mode model, and aims to support a loose coupling between the behavior of the page (Javascript code) and the appearance of the page (html and CSS);

Events first appeared in IE3 and Navigator3, and when released from IE4 and Navigator4, they provided similar but not identical APIs, which evolved in several versions; from DOM2 onwards, attempts were made to standardize DOM events in a logical way, standard browsers have basically implemented DOM2-level event modules, but earlier versions of IE (mainly IE8) still use their dedicated event systems;

The DOM2-level event module itself does not cover all event types; DOM3-level events add many event APIs, but are more cumbersome;

Event type:

is a string of characters that describe what type of event occurred, such as common events: click, load (page or image loading), mouseover (mouse hover), select (choose an input box in a form), submit (submit form), keypress (keyboard keys);

Event target: the associated object in which the event occurred;

Event handler: Events are usually used with functions, when the event occurs the function will not be executed, this function is called the event handler (function) or event listener or listener, is the function that responds to and processes the event (event listener); when the event handler registered on the object is called, it is called "fire" (trigger) and "dispatch" (dispatch) event;

Event Stream (Event Propagation):

An event flow is the process of which elements can fire their event handlers, that is, the order in which these elements that can trigger events receive events in a page;

IE and Netscape have differences in the order of occurrence (event flow) support, IE's event stream is a bubbling stream, while Netscape's event stream is a capture stream;

Bubbling events:

IE has an event stream called event bubbling;

Basic idea: Events are triggered in the order in which they propagate up from the most specific event target element (the node with the deepest nesting level in the document) to the least specific event target element (window or document object); as:

Events rise to the top like blisters in the hierarchy of the DOM, and the order of bubbling is: < div>, <body>, < html> and documentation;

Section 55 Event Event - Javascript for Web Front-End Development - Zero Point Programmer - Wang Wei

Bubbling event streams

Event bubbling is supported in all modern browsers; however, events are "bubbling" to the window object instead of the document object;

Captured events:

The event stream developed by the Netscape team is called event capturing, and its basic idea is the opposite of bubbling, which is to receive events from the least precise object (document object) to the most accurate object to receive events;

For example, the above event streams are captured in the following order: document, < html>, <body> and < div >, which can also be called top-down event models;

Section 55 Event Event - Javascript for Web Front-End Development - Zero Point Programmer - Wang Wei

Capture the flow of events

The purpose of event capture is to capture an event before it reaches its intended destination; modern browsers support capturing the event stream, which is not supported by earlier versions of IE;

The DOM2 event specification requires that events should start with a document object, but standard browsers start with a window object to capture events;

DOM Event Stream:

DOM supports two event models, capture events and bubbling events; DOM2 events stipulate that the event flow consists of three stages: the event capture stage, the target stage, and the event bubbling stage;

Section 55 Event Event - Javascript for Web Front-End Development - Zero Point Programmer - Wang Wei

The DOM event stream has three stages

In the DOM event stream, the actual target does not receive events during the capture phase; the target phase can be seen as part of the bubbling phase; the three-stage event stream touches all objects in the DOM, starting with the document object and ending at the document object;

The DOM2-level event specification explicitly requires that the capture phase does not involve the event target; however, modern browsers trigger events on the event object during the capture phase, with the result that there are two opportunities to manipulate the event on the target object;

Register event handlers/event listeners:

Functions called in response to an event are called event handles, or event listeners; the return value of an event handler is sometimes used to indicate whether the function adequately handled the event and to block the browser's default behavior;

There are three ways to register event handlers;

HTML event handler:

Specify in the event attribute of the HTML element that the name of the event attribute is "on" + the event name, and the value in the event attribute is the JavaScript code that can be executed, that is, the HTML event handler body;

You cannot use unescaped HTML syntax characters such as &, ", < >;

If the HTML event handler contains multiple Javascript statements, the statements must be separated by semicolons, or the property value must be broken so that it can span multiple lines, such as:

You can even define functions in it, such as:

HTML event handlers can also be defined elsewhere on the page, even in an external Javascript file;

HTML event handler, in the background will create a function that encapsulates the value of the element's attribute (attribute), that is, a function dynamically created by the interpreter, which also has a local variable event, that is, an event object;

This in the HTML event handler, points to the target element of the event, such as:

The scope in the HTML event handler is special, it can access any variables and objects in the global scope, but it extends the scope in such a way that it uses a width statement, that is, inside it can access the document and the members of the element itself as if it were a local variable, such as:

In this way, event handlers can easily access the properties (attributes) of their own elements themselves, such as:

If the current element is a form control element, the access form element (parent element) is also included in the scope, such as:

In this way, event handlers do not need to reference form elements to access other form controls, such as:

HTML event handler cons:

There is a time difference: if the event handler at the time of response may not yet have the conditions to execute, it will make an error; therefore, in order to avoid such an error, one must ensure that the relevant handler must be defined before the event is triggered; the other is that the relevant processing code can be encapsulated in try-catch, such as:

Its special way of extending the scope chain may lead to different results in different browsers; HTML and JS code coupling is high; given the above shortcomings, HTML event handlers are not very commonly used;

DOM0-level event handlers:

First get a reference to the element, and then assign the function to the corresponding event handler property of the element; by convention, the property name of the event handler begins with "on" and ends with the event name;

Advantages: simple and has the advantage of cross-browser;

Each element (including window and document) has its own event handler properties, and these property names are case-sensitive, usually all lowercase, even if the property name is composed of multiple words, such as onclick, onload, readystatechange, etc.;

Such event handlers are considered methods of the element, so the event handler at this point is run in the scope of the element, i.e. where this refers to the current element, that is, the event target;

Thus, any property and method of the element can be accessed through this;

Event handlers added in this way are handled during the bubbling phase of the event stream;

You can also delete an event handler like an event by setting it to null; for example:

Return values for HTML event handlers and DOM0-level event handlers: In some cases, you can set a return value for them; typically, returning false prevents the browser from default behavior, such as:

The disadvantage of DOM0 event handlers is that only one event handler can be registered for some kind of event of the target element, and if more than one is registered, the last registered one will overwrite the previous one, such as:

DOM2-level event handlers:

DOM2 defines a standard event model that defines the addEventListener() method for all elements that can be targeted by the event (including window and documentation) for handling (registering) specified event handlers;

The method accepts 3 parameters: the name of the event to be handled (cannot be added on, here is the standard event name), the function as the event handler and a Boolean value; the last parameter value, if true, means that the event handler is called in the capture stage, if false, means that the event handler is called in the bubbling phase, this parameter can also be ignored, default to false;

You can also register multiple event handlers for the same event;

Define both HTML event handlers or DOM0-level event handlers and DOM2-level event handlers, such as:

removeEventListener() remove event: The event handler added by addEventListener() can only be removed with the resolveEventListener() method, and when removed, the parameters passed in are the same as when the handler was added;

Anonymous functions cannot be removed if addEdEventListener() is added, such as:

However, it can be removed in disguise, such as:

If the event handler is added to the capture phase using addEventListener(), the event must be removed correctly by indicating in the resolveEventListener() that it is the capture phase, i.e. the third argument must also be the same;

You can also remove multiple events at once, such as:

Three events use the same handler, in which case all three event handlers are removed as long as one of the three events is triggered;

Three handlers are used;

If you want to get the Event event object, it is also specified in the parameters of the event handler; in addition, the thiss in the event handler also refers to the current element;

In general, event handlers are added to the bubbling phase of the event stream, which maximizes compatibility with a variety of browsers;

IE Event Handler:

IE9 and below do not support DOM events, but it implements DOM-like events, adding two methods for each element and window object: attachEvent ("event_name", fnHandler): used to attach events and event handlers to an object; detachEvent("event_name", fnHandler): clearing an object's events and event handlers Both methods accept the same two arguments: the event name and the handler, but the event name must start with "on", such as onclick;

(IE11 does not support, IE10 and below)

It is also possible to add multiple event handlers, but the order in which the handlers execute may differ from the DOM, such as;

IE10 and IE9 have the same order of execution as the DOM, but IE8 and below, the order of execution is the opposite of the DOM;

Since IE only supports event bubbling (event capture is not supported), the above method will be added to the bubbling phase;

The onclick on the window object is not triggered, indicating that IE's bubbling to the top layer is a document object;

Use detacheEvent() to remove event handlers added by attachEvent(), but you must also provide the same arguments, and it cannot remove added anonymous functions such as:

The main difference between using attachEvent() and using the DOM0-level method is the scope of the event handler, which runs in the global scope, so this is equal to window;

You can encapsulate a function that adds a certain type of event to an element and registers the associated event handler, and specifies its this as the event target, such as:

In the IE event handler, getting the Event event object is also different from the DOM;

Compatible with DOM and IE register event handlers:

Cross-platform add/remove event handlers:

Event Event Objects:

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

It is important to obtain event information, and generally the following information is obtained: the element (object) that caused the event, the type of event, the information of the mouse when the event occurred, the information of the keyboard when the event occurred, etc.; different events contain different information, for example, the mouse-caused event object will contain information related to the mouse position, and the event caused by the keyboard operation will contain information related to the key pressed;

Event objects are created only when an event occurs, and only event handlers can access them; event objects are destroyed after all event handlers are executed; all browsers support event objects, but support them in different ways, IE and the DOM implement event objects in two different ways;

Event objects for the DOM:

In the DOM, the event object must be passed to the event handler as a unique parameter, and both DOM0 and DOM2 use this parameter to obtain the event object;

When an event handler is added via an HTML attribute, the variable event holds the event object, such as:

Event class:

The Event interface represents an event that occurs in the DOM, which is a base class for other types of events, containing properties and methods that apply to all events; constructor: Event(), which creates and returns an Event object;

Syntax: event = new Event(typeArg, eventInit); argument: typeArg, a string, representing the name of the event being created; eventInit is optional, a dictionary object of type EventInit that accepts the following fields:

"bubbles", optional, of type Boolean, with a default value of false, indicating whether the event is bubbling;

"cancelable", optional, boolean type, default value is false, indicating whether the event can be canceled;

"composed", optional, Boolean type, default value is false, indicating whether the event will trigger a listener outside the Shadow DOM root node;

However, IE does not support it; once you have an event, you can add this event to an element and register its handler, such as:

Use the patchEvent() method to trigger the event, such as:

Since this event can bubble, the document descendant element can also trigger the event;

There are very few applications to return an event object using the Event constructor, and IE does not support it, so we will talk about another way to create a custom Event object later: document.createEvent("type"); for example:

Properties and methods of the Event object:

Property/method type read/write description

bubblesBooleanR indicates whether the event is bubbling;

CancelBubbleBooleanR/W setting whether to prevent bubbling, is the historical alias of the stopPropagation() method, set to true, you can prevent the event from continuing to bubble;

cancelableBooleanR indicates whether the default behavior of an event can be canceled;

composed BooleanR indicates that events can bubble through the barriers between the shadow DOM's regular DOM;

currentTargetElementR registers the elements of the current event;

deepPathArrayR consists of Array consisting of DOM nodes through which the event stream passes; none of the browsers implement it, but the Webkit browser implements a similar path property;

defaultPreventedBooleanR indicates whether the default behavior of events has been canceled, and DOM3 has been added as true, indicating that the preventDefault() method has been called;

eventPhaseIntegerR indicates which stage the event stream is being processed to, 1 for the capture phase, 2 for the target phase, and 3 for the bubbling phase;

Explicit Original Target TargetElementR event explicitly (explicitly) the original target; only FF implements this property;

originalTargetElementR resets the original target of the event; only FF implements this property;

ReturnValueBooleanR indicates whether the default behavior of the event is blocked, in the same way as the defaultPrevented attribute, a non-standard historical attribute introduced by the old version of IE, which is now included in the specification;

srcElementElementR event targets, the same as targets, introduced by the old version of IE, are now included in the specification;

TargetElementR event target, the element that triggers the event, is the same as srcElement;

Timestamp at the timestamp when the EventStampNumberR event was created, in milliseconds;

typeStringR is the type of event that is triggered, which is not case-sensitive;

isTrusted Boolean RDOM3 added, as true, indicating that events are generated by the browser (e.g. user clicks), and false is created by scripts;

composedPath(): Returns an Array of the path containing the event;

initEvent(): Initializes an event object created via document.createEvent();

preventDefault(): Cancels the default behavior of events, which can be used if cancelable is true;

StopImmediatePropagation() :D ADDED in OM3, cancels further capture or bubbling of events while preventing any event handlers from being called;

stopPropagation(): Cancels further capture or bubbling of events;

The Event object contains properties and methods related to the specific event in which it was created, but the types of events that are triggered are different, and the available properties and methods are different; the DOM event object also has the following common members;

detailIntegerR Details related to the event

viewAbstractViewR is associated with an abstract view of the event, equivalent to the window object in which the event occurred;

Subclasses of common Event:

CustomEvent: Custom event class;

DeviceOrientationEvent: Rotate the mobile device event class; (e.g., get the x, y, and Z axe angles of the rotation of an event, etc.)

DragEvent: Drag-and-drop event class, which inherits both Event and MouseEvent classes;

ErrorEvent: Error event class;

FocusEvent: Represents a focus-related event class, inherited from the UIEvent class;

KeyboardEvent: Keyboard event class

MouseEvent: Mouse event class, inherited from the UIEvent class;

MutationEvent: Class of change events;

TouchEvent: Touch event class, inherited from the UIEvent class;

UIEvent; user interface event class;

WheelEvent: Mouse wheel or similar input device event class;

type attribute:

When you need to handle multiple events through a function, you can use the type property;

deepPath property: Returns the Array consisting of DOM nodes through which the event stream passes; all browsers do not implement it, but the Webkit browser implements a similar path property;

The end returned is basically the same as path, but IE does not support this method;

bubbles attribute:

bubbles returns a Boolean value indicating whether the current event will bubble up to the upper elements on the DOM tree;

For example, you can check whether the property is bubbling, such as:

this, currentTarget, target, and srcElement attributes:

Inside the event handler, this is always equal to the value of currentTarget, which contains only the actual target of the event; if the event handler is assigned directly to the target element, this, currentTarget, and target contain the same value;

If an event handler is added to the element's parent node, the three are different, such as:

When registering the same event handler with multiple elements, the currentTarget property is useful, such as:

For the srcElement property, it was originally introduced by IE6, pointing to the same object as the target of the DOM event, although it is now included in the standard, it is not supported in some mobile browsers, so in the production environment, just to be compatible with the old version of IE, it is not used as a standard property;

eventPhase attribute:

EventPhase property of an event object, which returns an integer value that determines which stage of the event flow the event is currently in, if no event is being processed, the property returns Event.NONE with a value of 0 (this value generally does not appear), if the event handler is called during the capture phase, the property returns Event.CAPTURING_PHASE, a value of 1, or Event.AT if the event handler is on the target object TARGET, with a value of 2, returns Event.BUBBLING_PHASE if the event handler is called during the bubbling phase, with a value of 3;

The event handler call to the target object itself is stage 2;

If the event handler is registered as captured, then it is called during the 1st phase of event propagation;

Register captured event handlers separately:

Event capture provides an opportunity to view events before they reach the target; event capture can be used for program debugging, or for the event cancellation technique described later, filtering out events so that the target event handler is never invoked;

Event capture is often used to handle mouse drag-and-drop because the location to handle drag-and-drop events cannot be a child element inside this element;

example:

Cancel an event (default behavior):

Use the return false value in HTML event handlers and DOM0-level event handlers to cancel the default behavior of events; for example: block hyperconnect navigation behavior (the default behavior of links is to navigate to the URL specified by href when clicked);

When working with Event objects, the default behavior of preventing (or canceling) specific events can be blocked (or called canceled) using the RiskDefault() method;

When using the preventDefault() method, the default behavior of events can only be blocked if the cancelable attribute is true; for example:

Example: Validating data input, such as:

The defaultPrevented property of the event object, which is new to the DOM3 event, indicates the state of the current cancel event, the default is false, if the preventDefault() method is called, the property value is true, such as:

returnValue attribute: The same function as the preventDefault() and defaultPrevented attributes, a non-standard historical attribute introduced by the old version of IE, which is now included in the specification; by default, it is set to true, that is, default operations are allowed, and setting this property to false prevents default operations;

To cancel event propagation:

Use stopPropagation() for immediately stopping the propagation of events in the DOM hierarchy, i.e. canceling further event capture or bubbling, such as:

If multiple event handlers are registered with the same object, even if the stopPropagation() method is called, all the event handlers are executed, such as:

cancelBubble, Boolean value, readable and writable, set whether to prevent bubbling, is the historical alias of the stopPropagation() method, set to true, you can prevent the event from continuing to bubble;

A new stopImmediatePropagation() method has been added to the event object in DOM3, which is similar to the stopPropagation() method, which prevents event propagation, but also prevents calls to other event handlers of the same event registered on the same object, such as:

If multiple event handlers are registered on the same event type of the same element, when this event fires, they are called in the order in which it was added, and if the stopImmediatePropagation() method is executed in one of the event handlers, none of the remaining event listeners will be called, such as:

Other properties: timestamp, read-only, timestamp at event creation in milliseconds;

For example, you can calculate the speed at which the mouse moves, showing the number of pixels moving per second, such as:

isTrusted, a read-only Boolean value, added to DOM3, as true, indicating that the event is generated by the browser (e.g. user clicks), and false is created by the script;

The isTrusted property is generally used to check whether an event is trusted, and if it is a user operation, it is certainly trustworthy, but in IE, all events are trustworthy except those created using the createEvent() method; for example:

Event objects in IE:

In IE, there are several ways to access the event object, depending on the method that specifies the event handler; when using DOM0-level methods, the event object is a property of the window object event, such as:

If added with attachEvent(), then an event object is passed into the event handler function as an argument; even so, the event object can be accessed through the window object;

If you specify an event handler through an HTML attribute, then the event object can be accessed through a variable called event:

Event object properties and methods in IE:

The event object in the IE also contains properties and methods related to the event in which it was created; many of these properties and methods correspond to the event object properties and methods of the DOM; these properties and methods also vary depending on the event type, and the following are common members: property/method type read/write descriptions

cancelBubble BooleanR/W defaults to false, and setting it to true cancels event bubbling (same as stopPropagation() method);

returnValue BooleanR/W defaults to true, and setting it to false cancels the default behavior of events (the same as the defaultDefault() method in the DOM);

srcElement ElementR event target (same as target attribute in the DOM);

Type The type of event that the StringR is triggering

The scope of an event handler in IE is determined based on how it is specified, so it cannot be assumed that this will always be equal to the event target, so it is best to use event.srcElement, such as:

The returnValue property is equivalent to the defaultDefault() method in the DOM, and their effect is to cancel the default behavior of a given event, which defaults to true, as long as the property value is set to false, the default behavior can be blocked, such as:

The cancelBubble property has the same function as the stopPropagation() method in the DOM, both are used to stop event propagation, but because IE does not support event capture, cancelBubble can only cancel event bubbling, while stopPropagation() can cancel event capture and bubbling at the same time;

Add cross-browser events to the eventutil .js;

apply:

Section 55 Event Event - Javascript for Web Front-End Development - Zero Point Programmer - Wang Wei

Read on