Event object
overview
After the event occurs, an event object will be generated and passed to the listening function as a parameter. The browser provides an object natively Event
, and all events are instances of this object, or inherit Event.prototype
the object.
Event
The object itself is a constructor that can be used to generate new instances.
event = new Event(type, options);
Event
The constructor accepts two parameters. The first parameter type
is a string representing the name of the event; the second parameter options
is an object representing the configuration of the event object. This object mainly has the following two properties.
-
bubbles
: Boolean value, optional, default isfalse
, indicates whether the event object is bubbling. -
cancelable
: Boolean value, optional, default isfalse
, indicating whether the event can be canceled, that is, whetherEvent.preventDefault()
the event can be canceled by using the function. Once an event is canceled, it is as if it never happened, and the browser's default behavior for that event is not triggered.
var ev = new Event( 'look', { 'bubbles': true, 'cancelable': false } ); document.dispatchEvent(ev);
The above code creates a new look
event instance, and then uses dispatchEvent
the method to trigger the event.
bubbles
Note that if the attribute is not explicitly specified true
, the generated event can only trigger the listener function in the "capture phase".
// HTML code is // <div><p>Hello</p></div> var div = document.querySelector('div'); var p = document.querySelector('p'); function callback(event) { var tag = event.currentTarget.tagName; console.log('Tag: ' + tag); // no output } div.addEventListener('click', callback, false); var click = new Event('click'); p.dispatchEvent(click);
In the above code, p
the element emits an click
event, which does not bubble by default. div.addEventListener
The method specifies listening during the bubbling phase, so the listening function will not trigger. If written div.addEventListener('click', callback, true)
, this event can be listened to during the "capture phase".
On the other hand, if this event div
fires on the element.
div.dispatchEvent(click);
Then, no matter whether div
the element is listening in the bubbling phase or in the capturing phase, the listening function will be triggered. Because div
the element is the target of the event at this time, there is no question of whether it is bubbling, and div
the element will always receive the event, thus causing the listening function to take effect.
instance attribute
Event.bubbles,Event.eventPhase
Event.bubbles
Property returns a boolean indicating whether the current event will bubble. This attribute is read-only, and is generally used to know whether the Event instance can bubble. As mentioned earlier, unless explicitly stated, Event
the events generated by the constructor are not bubbling by default.
Event.eventPhase
Property returns an integer constant representing the current phase of the event. This property is read-only.
var phase = event.eventPhase;
Event.eventPhase
There are four possible return values for .
-
0, the event is not currently occurring.
-
1. The event is currently in the capture phase, that is, it is in the process of propagating from the ancestor node to the target node.
-
2. The event reaches the target node, that is,
Event.target
the node pointed to by the attribute. -
3. The event is in the bubbling stage, that is, it is in the process of back propagation from the target node to the ancestor node.
Event.cancelable,Event.cancelBubble,event.defaultPrevented
Event.cancelable
Property returns a boolean indicating whether the event can be canceled. This property is read-only and is generally used to understand the characteristics of the Event instance.
Most browser's native events are cancelable. For example, to cancel click
the event, clicking on the link will have no effect. But unless explicitly stated, Event
the events generated by the constructor cannot be canceled by default.
var evt = new Event('foo'); evt.cancelable // false
When Event.cancelable
the property true
is , calling Event.preventDefault()
can cancel this event, preventing the browser's default behavior for this event.
If the event cannot be canceled, the call Event.preventDefault()
has no effect. So before using this method, it is best to use Event.cancelable
attributes to determine whether it can be canceled.
function preventEvent(event) { if (event.cancelable) { event.preventDefault(); } else { console.warn('This event couldn\'t be canceled.'); console.dir(event); } }
Event.cancelBubble
The attribute is a boolean value, if set true
, it is equivalent to execution Event.stopPropagation()
, which can prevent the propagation of the event.
Event.defaultPrevented
The property returns a boolean indicating whether the Event.preventDefault
method was called by the event. This property is read-only.
if (event.defaultPrevented) { console.log('The event has been canceled'); }
Event.currentTarget,Event.target
After an event occurs, it will go through two stages of capture and bubbling, and pass through multiple DOM nodes in turn. Therefore, any event has two nodes associated with the event, one is the original trigger node of the event ( Event.target
), and the other is the node through which the event is currently passing ( Event.currentTarget
). The former are usually descendant nodes of the latter.
Event.currentTarget
The property returns the node where the event is currently located, that is, the node through which the event is currently passing, that is, the node where the listener function currently being executed is located. As the event propagates, the value of this property changes.
Event.target
The property returns the node that originally fired the event, that is, the node where the event originally occurred. This property does not change as the event propagates.
During the event propagation process, the values of the listener functions Event.target
and Event.currentTarget
attributes of different nodes are different.
// HTML code is // <p id="para">Hello <em>World</em></p> function hide(e) { // Regardless of clicking Hello or World, always return true console.log(this === e.currentTarget); // Click Hello, return true // Click World, return false console.log(this === e.target); } document.getElementById('para').addEventListener('click', hide, false);
In the above code, <em>
if <p>
the child node is clicked <em>
or clicked <p>
, it will cause the execution of the monitoring function. At this time, e.target
always point to the node at the original click position, and e.currentTarget
point to the node that is passing through during the event propagation process. Since the listener function will only be triggered when the event passes, it e.currentTarget
is always equivalent to the inside of the listener function this
.
Event.type
Event.type
Property returns a string representing the event type. The type of event is specified when the event is generated. This property is read-only.
var evt = new Event('foo'); evt.type // "foo"
Event.timeStamp
Event.timeStamp
Property returns a millisecond timestamp representing when the event occurred. It is calculated relative to the successful loading of the page.
var evt = new Event('foo'); evt.timeStamp // 3683.6999999995896
Its return value may be an integer or a decimal (high precision timestamp), depending on the browser settings.
Below is an example that calculates the speed of mouse movement, showing the number of pixels moved per second.
var previousX; var previousY; var previousT; window.addEventListener('mousemove', function(event) { if ( previousX !== undefined && previousY !== undefined && previousT !== undefined ) { var deltaX = event.screenX - previousX; var deltaY = event.screenY - previousY; var deltaD = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); var deltaT = event.timeStamp - previousT; console.log(deltaD / deltaT * 1000); } previousX = event.screenX; previousY = event.screenY; previousT = event.timeStamp; });
Event.isTrusted
Event.isTrusted
The property returns a Boolean value indicating whether the event was generated by actual user action. For example, when the user clicks on a link click
, an event is generated by the user; Event
the event generated by the constructor is generated by the script.
var evt = new Event('foo'); evt.isTrusted // false
In the above code, evt
the object is generated by the script, so isTrusted
the property is returned false
.
Event.detail
Event.detail
Properties are only available for browser UI (User Interface) events. This property returns a value that represents some kind of information about the event. The specific meaning is related to the event type. For example, for click
the and dblclick
event, Event.detail
it is the number of times the mouse is pressed ( 1
indicates single click, 2
double click, 3
triple click); for the mouse wheel event, Event.detail
it is the distance of the scroll wheel in the positive direction, and the negative value is the distance of the negative scroll. is a multiple of 3.
// The HTML code is as follows // <p>Hello</p> function giveDetails(e) { console.log(e.detail); } document.querySelector('p').onclick = giveDetails;
instance method
Event.preventDefault()
Event.preventDefault
Method cancels the browser's default behavior for the current event. For example, after clicking a link, the browser will jump to another page by default. After using this method, it will not jump; scrolled. The prerequisite for this method to take effect is that cancelable
the property of the event object is true
, and if so false
, calling this method has no effect.
Note that this method only cancels the default effect of the event on the current element, and does not prevent the propagation of the event. If you want to prevent propagation, you can use the stopPropagation()
or stopImmediatePropagation()
method.
// HTML code is // <input type="checkbox" id="my-checkbox" /> var cb = document.getElementById('my-checkbox'); cb.addEventListener( 'click', function (e){ e.preventDefault(); }, false );
In the above code, the default behavior of the browser is to click the radio button to select it. Canceling this behavior will result in the radio button not being selected.
Using this method, you can set validation conditions for the text input box. If the user's input does not meet the criteria, characters cannot be entered into the text box.
// HTML code is // <input type="text" id="my-input" /> var input = document.getElementById('my-input'); input.addEventListener('keypress', checkName, false); function checkName(e) { if (e.charCode < 97 || e.charCode > 122) { e.preventDefault(); } }
After the above code keypress
sets the listener function for the event of the text box, only lowercase letters can be input, otherwise the default behavior of the input event (writing into the text box) will be cancelled, resulting in the inability to input content into the text box.
Event.stopPropagation()
stopPropagation
The method prevents the event from continuing to propagate in the DOM, and prevents triggering of listener functions defined on other nodes, but does not include other event listener functions on the current node.
function stopEvent(e) { e.stopPropagation(); } el.addEventListener('click', stopEvent, false);
In the above code, click
the event will not bubble up further to el
the node's parent node.
Event.stopImmediatePropagation()
Event.stopImmediatePropagation
method prevents other listener functions of the same event from being called, no matter the listener function is defined on the current node or other nodes. That is, the method prevents the propagation of events Event.stopPropagation()
more thoroughly than .
If the same node specifies multiple listener functions for the same event, these functions will be called sequentially according to the order in which they are added. As long as one of the listener functions calls Event.stopImmediatePropagation
the method, the other listener functions will not be executed again.
function l1(e){ e.stopImmediatePropagation(); } function l2(e){ console.log('hello world'); } el.addEventListener('click', l1, false); el.addEventListener('click', l2, false);
The above code is el
on the node, and two listener functions and click
are added to the event . Since the method was called , it will not be called.l1
l2
l1
event.stopImmediatePropagation
l2
Event.composedPath()
Event.composedPath()
Returns an array whose members are the bottom-level node of the event and all the upper-level nodes that bubble through in turn.
// The HTML code is as follows // <div> // <p>Hello</p> // </div> var div = document.querySelector('div'); var p = document.querySelector('p'); div.addEventListener('click', function (e) { console.log(e.composedPath()); }, false); // [p, div, body, html, document, Window]
In the above code, click
the bottom-level node of the event is p
, and the upward sequence is div
, body
, html
, document
, Window
.