Event Object

Overview

After the event occurs, an event object will be generated and passed to the listener function as a parameter. The browser natively provides an Event object, all events are instances of this object, or inherited from the Event.prototype object.

The Event object itself is a constructor, which can be used to generate new instances.

event = new Event(type, options);

The Event 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. The object mainly has the following two attributes.

-bubbles: Boolean value, optional, default is false, indicating whether the event object is bubbling. -cancelable: Boolean value, optional, default is false, indicating whether the event can be cancelled, that is, whether the event can be cancelled with Event.preventDefault(). Once the event is cancelled, it seems that it has never happened, and will not trigger the browser's default behavior on the event.

var ev = new Event("look", {
  bubbles: true,
  cancelable: false,
});
document.dispatchEvent(ev);

The above code creates a look event instance, and then uses the dispatchEvent method to trigger the event.

Note that if the bubbles attribute is not explicitly specified as 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, the p element emits a click event, which does not bubble by default. The div.addEventListener method specifies to listen in the bubbling phase, so the listener function will not be triggered. If written as div.addEventListener('click', callback, true), then this event can be listened to in the "capture phase".

On the other hand, if this event is triggered on the div element.

div.dispatchEvent(click);

Then, regardless of whether the div element is listening in the bubbling phase or in the capture phase, the listening function will be triggered. Because the div element is the target of the event at this time, there is no question of whether bubbling or not. The div element always receives the event, which causes the listener function to take effect.

Instance attributes

Event.bubbles, Event.eventPhase

The Event.bubbles property returns a boolean value 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 declared, the events generated by the Event constructor are not bubbling by default.

The Event.eventPhase property returns an integer constant that represents the current phase of the event. This attribute is read-only.

var phase = event.eventPhase;

There are four possibilities for the return value of Event.eventPhase.

-0, the event has not occurred currently. -1. The event is currently in the capture phase, that is, in the process of propagating from the ancestor node to the target node. -2. The event reaches the target node, which is the node pointed to by the Event.target property. -3. The event is in the bubbling phase, that is, in the process of back propagation from the target node to the ancestor node.

Event.cancelable, Event.cancelBubble, event.defaultPrevented

The Event.cancelable property returns a boolean value indicating whether the event can be cancelled. This attribute is read-only and is generally used to understand the characteristics of the Event instance.

Most browsers’ native events can be cancelled. For example, if you cancel the click event, clicking the link will be invalid. But unless explicitly declared, the event generated by the Event constructor cannot be cancelled by default.

var evt = new Event("foo");
evt.cancelable; // false

When the Event.cancelable property is true, calling Event.preventDefault() can cancel the event and prevent the browser from defaulting on the event.

If the event cannot be cancelled, calling Event.preventDefault() will have no effect. So before using this method, it is best to use the Event.cancelable property to determine whether it can be cancelled.

function preventEvent(event) {
  if (event.cancelable) {
    event.preventDefault();
  } else {
    console.warn("This event couldn't be canceled.");
    console.dir(event);
  }
}

The Event.cancelBubble property is a boolean value. If set to true, it is equivalent to executing Event.stopPropagation(), which can prevent the propagation of the event.

The Event.defaultPrevented property returns a boolean value indicating whether the event has called the Event.preventDefault method. This attribute is read-only.

if (event.defaultPrevented) {
  console.log("The event has been cancelled");
}

Event.currentTarget, Event.target

After the event occurs, it will go through two stages of capture and bubbling, passing through multiple DOM nodes in turn. Therefore, any event has two nodes related to the event, one is the original trigger node of the event (Event.target), and the other is the node that the event is currently passing through (Event.currentTarget). The former is usually a descendant node of the latter.

The Event.currentTarget property returns the node where the event is currently located, that is, the node that the event is currently passing through, that is, the node where the currently executing listener function is located. As the event propagates, the value of this property will change.

The Event.target property returns the node that originally triggered the event, that is, the node where the event originally occurred. This property will not change as the event propagates.

During the event propagation process, the values ​​of the Event.target and Event.currentTarget properties inside the monitoring function of different nodes are different.

// HTML code is
// <p id="para">Hello <em>World</em></p>
function hide(e) {
  // No matter click 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> is a child node of <p>, clicking on <em> or clicking on <p> will cause the monitoring function to execute. At this time, e.target always points to the node at the original click position, and e.currentTarget points to the node that is passing during the event propagation process. Since the listener function is triggered only when the event passes, e.currentTarget is always equivalent to this inside the listener function.

Event.type

The Event.type property returns a string indicating the type of event. The type of event is specified when the event is generated. This attribute is read-only.

var evt = new Event("foo");
evt.type; // "foo"

Event.timeStamp

The Event.timeStamp property returns a millisecond timestamp indicating the time when the event occurred. It is calculated relative to the successful page load.

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.

The following is an example of calculating the speed of the mouse, 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

The Event.isTrusted property returns a boolean value indicating whether the event was generated by a real user behavior. For example, a user clicking on a link will generate a click event, which is generated by the user; the event generated by the Event constructor is generated by a script.

var evt = new Event("foo");
evt.isTrusted; // false

In the above code, the evt object is generated by the script, so the isTrusted property returns false.

Event.detail

The Event.detail property is only available for browser UI (user interface) events. This property returns a numeric value, which represents some information about the event. The specific meaning is related to the event type. For example, for click and dblclick events, Event.detail is the number of times the mouse is pressed (1 means single click, 2 means double click, and 3 means triple click); for mouse wheel events, Event.detail is the distance of the scroll wheel in the positive direction, and the negative value is the distance of the negative direction. The return value is always a multiple of 3.

// HTML code is as follows
// <p>Hello</p>
function giveDetails(e) {
  console.log(e.detail);
}

document.querySelector("p").onclick = giveDetails;

Example method

Event.preventDefault()

The Event.preventDefault method cancels the browser's default behavior for the current event. For example, after clicking the link, the browser will jump to another page by default. After using this method, it will not jump; for another example, press the space bar and the page will scroll down for a certain distance. After using this method, it will not Rolled up. The premise for this method to take effect is that the cancelable property of the event object is true, if it is 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. If this behavior is canceled, the radio button cannot be selected.

Using this method, you can set the check condition for the text input box. If the user's input does not meet the conditions, the 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 sets the listening function for the keypress 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 enter the text box.

Event.stopPropagation()

The stopPropagation method prevents the event from continuing to propagate in the DOM, and prevents the triggering of monitoring functions defined on other nodes, but does not include other event monitoring functions on the current node.

function stopEvent(e) {
  e.stopPropagation();
}

el.addEventListener("click", stopEvent, false);

In the above code, the click event will not bubble to the parent node of the el node.

Event.stopImmediatePropagation()

The Event.stopImmediatePropagation method prevents other listener functions of the same event from being called, regardless of whether the listener function is defined in the current node or other nodes. In other words, this method prevents the propagation of events, which is more thorough than Event.stopPropagation().

If the same node specifies multiple listener functions for the same event, these functions will be called in sequence according to the order in which they were added. As long as one of the monitoring functions calls the Event.stopImmediatePropagation method, the other monitoring functions will no longer be executed.

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 on the el node, and two listener functions l1 and l2 are added for the click event. Since l1 calls the event.stopImmediatePropagation method, so l2 will not be called.

Event.composedPath()

Event.composedPath() returns an array, the members are the lowest node of the event and all upper nodes that bubble through in turn.

// 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, the bottom node of the click event is p, and upwards are div, body, html, document, and Window.