Mouse event

Types of mouse events

Mouse events refer to events related to the mouse, inheriting the MouseEvent interface. The specific incidents mainly include the following.

-click: Triggered when the mouse is pressed (usually the main button is pressed). -dblclick: Triggered when the mouse is double-clicked on the same element. -mousedown: Triggered when the mouse button is pressed. -mouseup: Triggered when the pressed mouse button is released. -mousemove: Triggered when the mouse moves inside a node. When the mouse continues to move, the event will be triggered continuously. In order to avoid performance problems, it is recommended to make some restrictions on the monitoring function of this event, for example, it can only run once within a period of time. -mouseenter: Triggered when the mouse enters a node. Entering a child node will not trigger this event (see later for details). -mouseover: Triggered when the mouse enters a node. Entering a child node will trigger this event again (see later for details). -mouseout: Triggered when the mouse leaves a node, this event will also be triggered when leaving the parent node (see later for details). -mouseleave: Triggered when the mouse leaves a node, leaving the parent node will not trigger this event (see later for details). -contextmenu: Triggered when the right mouse button is pressed (before the context menu appears), or when the "context menu key" is pressed. -wheel: Triggered when the mouse wheel is rolled. This event inherits the WheelEvent interface.

The click event means that the user first completes the mousedown action at the same location, and then completes the mouseup action. Therefore, the trigger sequence is, mousedown triggers first, mouseup then triggers, and click triggers last.

The dblclick event will be triggered after mousedown, mouseup, and click.

The mouseover event and the mouseenter event are both triggered when the mouse enters a node. The difference between the two is that the mouseenter event is only triggered once, and as long as the mouse moves inside the node, the mouseover event will be triggered multiple times on the child nodes.

/* HTML code is as follows
 <ul>
   <li>item 1</li>
   <li>item 2</li>
  <li>item 3</li>
 </ul>
*/

var ul = document.querySelector("ul");

// After entering the ul node, the mouseenter event will only be triggered once
// As long as the mouse moves within the node in the future, this event will not be triggered again
// event.target is the ul node
ul.addEventListener(
  "mouseenter",
  function (event) {
    event.target.style.color = "purple";
    setTimeout(function () {
      event.target.style.color = "";
    }, 500);
  },
  false
);

// After entering the ul node, as long as you move on the child node, the mouseover event will be triggered multiple times
// event.target is the li node
ul.addEventListener(
  "mouseover",
  function (event) {
    event.target.style.color = "orange";
    setTimeout(function () {
      event.target.style.color = "";
    }, 500);
  },
  false
);

In the above code, entering the child node inside the parent node will not trigger the mouseenter event, but will trigger the mouseover event.

The mouseout event and the mouseleave event are both triggered when the mouse leaves a node. The difference between the two is that when leaving a child element inside the parent element, the mouseleave event will not be triggered, but the mouseout event will be triggered.

/* HTML code is as follows
 <ul>
   <li>item 1</li>
   <li>item 2</li>
  <li>item 3</li>
 </ul>
*/

var ul = document.querySelector("ul");

// First enter the ul node, and then move inside the node without triggering the mouseleave event
// Trigger mouseleave once only when leaving the ul node
// event.target is the ul node
ul.addEventListener(
  "mouseleave",
  function (event) {
    event.target.style.color = "purple";
    setTimeout(function () {
      event.target.style.color = "";
    }, 500);
  },
  false
);

// First enter the ul node, and then move inside the node, the mouseout event will be triggered multiple times
// event.target is the li node
ul.addEventListener(
  "mouseout",
  function (event) {
    event.target.style.color = "orange";
    setTimeout(function () {
      event.target.style.color = "";
    }, 500);
  },
  false
);

In the above code, leaving the child node inside the parent node will not trigger the mouseleave event, but will trigger the mouseout event.

MouseEvent interface overview

The MouseEvent interface represents mouse-related events, such as clicking (click), double-clicking (dblclick), releasing the mouse button (mouseup), pressing the mouse button (mousedown) and other actions. The event objects generated are all MouseEvent Instance. In addition, scroll wheel events and drag events are also instances of MouseEvent.

The MouseEvent interface inherits the Event interface, so it has all the properties and methods of Event. It also has its own properties and methods.

The browser natively provides a MouseEvent constructor to create a new instance of MouseEvent.

var event = new MouseEvent(type, options);

The MouseEvent constructor accepts two parameters. The first parameter is a string, which represents the name of the event; the second parameter is an event configuration object, which is optional. In addition to the instance configuration properties of the Event interface, the object can be configured with the following properties, all of which are optional.

-screenX: numeric value, the horizontal position of the mouse relative to the screen (unit pixel), the default value is 0, setting this property will not move the mouse. -screenY: Numeric value, the vertical position of the mouse relative to the screen (unit pixel), other things are the same as screenX. -clientX: numeric value, the horizontal position of the mouse relative to the program window (unit pixel), the default value is 0, setting this property will not move the mouse. -clientY: Numeric value, the vertical position of the mouse relative to the program window (unit pixel), other things are the same as clientX. -ctrlKey: Boolean value, whether the Ctrl key is pressed at the same time, the default value is false. -shiftKey: Boolean value, whether the Shift key is pressed at the same time, the default value is false. -altKey: Boolean value, whether to press the Alt key at the same time, the default value is false. -metaKey: Boolean value, whether to press the Meta key at the same time, the default value is false. -button: Numeric value, which indicates which mouse button was pressed, the default value is 0, which means that the primary button is pressed (usually the left button of the mouse) or the current event does not define this attribute; 1 means press auxiliary Key (usually the middle button of the mouse), 2 means to press the secondary key (usually the right button of the mouse). -buttons: Numeric value, indicating which buttons of the mouse are pressed. It is a three-bit binary value, and the default is 0 (no key is pressed). 1 (binary 001) means pressing the primary key (usually the left button), 2 (binary 010) means pressing the secondary key (usually the right button), 4 (binary 100) Indicates to press the auxiliary key (usually the middle key). Therefore, if it returns 3 (binary 011), it means that the left button and the right button have been pressed at the same time. -relatedTarget: Node object, which represents the related node of the event, the default is null. In mouseenter and mouseover events, it indicates the element node where the mouse has just left; in mouseout and mouseleave events, it indicates the element node where the mouse is entering.

Below is an example.

function simulateClick() {
  var event = new MouseEvent("click", {
    bubbles: true,
    cancelable: true,
  });
  var cb = document.getElementById("checkbox");
  cb.dispatchEvent(event);
}

The above code generates a mouse click event and triggers the event.

Instance attributes of MouseEvent interface

MouseEvent.altKey, MouseEvent.ctrlKey, MouseEvent.metaKey, MouseEvent.shiftKey

The four properties of MouseEvent.altKey, MouseEvent.ctrlKey, MouseEvent.metaKey, and MouseEvent.shiftKey all return a Boolean value, which indicates whether the corresponding key is pressed when the event occurs. They are all read-only attributes.

-altKey attribute: Alt key -ctrlKey attribute: Ctrl key -metaKey attribute: Meta key (Mac keyboard is a small flower with four petals, Windows keyboard is Windows key) -shiftKey attribute: Shift key

// HTML code is as follows
// <body onclick="showKey(event)">
function showKey(e) {
  console.log("ALT key pressed: " + e.altKey);
  console.log("CTRL key pressed: " + e.ctrlKey);
  console.log("META key pressed: " + e.metaKey);
  console.log("SHIFT key pressed: " + e.shiftKey);
}

In the above code, clicking the webpage will output whether the corresponding key is pressed at the same time.

MouseEvent.button, MouseEvent.buttons

The MouseEvent.button property returns a value indicating which button of the mouse was pressed when the event occurred. This attribute is read-only.

-0: Press the main button (usually the left button), or the event does not initialize this attribute (such as the mousemove event). -1: Press the auxiliary key (usually the middle button or the scroll wheel button). -2: Press the key a second time (usually the right button).

// HTML code is
// <button onmouseup="whichButton(event)">click</button>
var whichButton = function (e) {
  switch (e.button) {
    case 0:
      console.log("Left button clicked.");
      break;
    case 1:
      console.log("Middle button clicked.");
      break;
    case 2:
      console.log("Right button clicked.");
      break;
    default:
      console.log("Unexpected code: " + e.button);
  }
};

The MouseEvent.buttons property returns a three-bit value indicating which keys were pressed at the same time. It is used to handle situations where multiple mouse buttons are pressed at the same time. This attribute is read-only.

-1: Binary is 001 (decimal 1), which means pressing the left button. -2: Binary is 010 (decimal 2), which means pressing the right button. -4: Binary is 100 (decimal 4), which means to press the middle button or the scroll wheel button.

When multiple keys are pressed at the same time, the bit corresponding to each pressed key will have a value. For example, pressing the left and right buttons at the same time will return 3 (binary is 011).

MouseEvent.clientX, MouseEvent.clientY

The MouseEvent.clientX property returns the horizontal coordinate (in pixels) of the mouse position relative to the upper left corner of the browser window, and the MouseEvent.clientY property returns the vertical coordinate. Both of these attributes are read-only.

// HTML code is
// <body onmousedown="showCoords(event)">
function showCoords(evt) {
  console.log(
    "clientX value: " +
      evt.clientX +
      "\n" +
      "clientY value: " +
      evt.clientY +
      "\n"
  );
}

These two properties also have aliases MouseEvent.x and MouseEvent.y respectively.

MouseEvent.movementX, MouseEvent.movementY

The MouseEvent.movementX property returns the horizontal distance (in pixels) between the current position and the previous mousemove event. Numerically, it is equal to the following calculation formula.

currentEvent.movementX = currentEvent.screenX - previousEvent.screenX;

The MouseEvent.movementY property returns the vertical distance (in pixels) between the current position and the previous mousemove event. Numerically, it is equal to the following calculation formula.

currentEvent.movementY = currentEvent.screenY-previousEvent.screenY.

Both of these attributes are read-only.

MouseEvent.screenX, MouseEvent.screenY

The MouseEvent.screenX property returns the horizontal coordinate (in pixels) of the mouse position relative to the upper left corner of the screen, and the MouseEvent.screenY property returns the vertical coordinate. Both of these attributes are read-only.

// HTML code is as follows
// <body onmousedown="showCoords(event)">
function showCoords(evt) {
  console.log(
    "screenX value: " + evt.screenX + "\n",
    "screenY value: " + evt.screenY + "\n"
  );
}

MouseEvent.offsetX, MouseEvent.offsetY

The MouseEvent.offsetX property returns the horizontal distance (in pixels) between the mouse position and the padding edge on the left side of the target node, and the MouseEvent.offsetY property returns the vertical distance from the padding edge above the target node. Both of these attributes are read-only.

/* HTML code is as follows
  <style>
    p {
      width: 100px;
      height: 100px;
      padding: 100px;
    }
  </style>
  <p>Hello</p>
*/
var p = document.querySelector("p");
p.addEventListener(
  "click",
  function (e) {
    console.log(e.offsetX);
    console.log(e.offsetY);
  },
  false
);

In the above code, if the mouse clicks at the center of the p element, it will return 150 150. Therefore, the distance from the center to the left and upper edges of padding is equal to the width of padding (100 pixels) plus half the width of the element content area (50 pixels).

MouseEvent.pageX, MouseEvent.pageY

The MouseEvent.pageX property returns the distance between the mouse position and the left edge of the document (in pixels), and the MouseEvent.pageY property returns the distance (in pixels) from the upper edge of the document. Their return values ​​all include the invisible parts of the document. Both of these attributes are read-only.

/* HTML code is as follows
  <style>
    body {
      height: 2000px;
    }
  </style>
*/
document.body.addEventListener(
  "click",
  function (e) {
    console.log(e.pageX);
    console.log(e.pageY);
  },
  false
);

In the above code, the page height is 2000 pixels, which will produce a vertical scroll bar. Scroll to the bottom of the page and click the mouse to output the value of pageY close to 2000.

MouseEvent.relatedTarget

The MouseEvent.relatedTarget property returns the related node of the event. For events that have no associated nodes, this property returns null. This attribute is read-only.

The following table lists the target attribute value and the relatedTarget attribute value meaning of different events.

Event nametarget attributerelatedTarget attribute
focusinNode receiving focusNode losing focus
focusoutThe node that loses focusThe node that receives the focus
mouseenternode to enternode to leave
mouseleaveThe node about to leaveThe node about to enter
mouseoutThe node about to leaveThe node about to enter
mouseovernode to enternode to leave
dragenterThe node about to enterThe node about to leave
dragexitnode to leavenode to enter

Below is an example.

/*
  HTML code is as follows
  <div id="outer" style="height:50px;width:50px;border:1px solid black;">
    <div id="inner" style="height:25px;width:25px;border:1px solid black;"></div>
  </div>
*/

var inner = document.getElementById("inner");
inner.addEventListener(
  "mouseover",
  function (event) {
    console.log("Enter" + event.target.id + "Leave" + event.relatedTarget.id);
  },
  false
);
inner.addEventListener("mouseenter", function (event) {
  console.log("Enter" + event.target.id + "Leave" + event.relatedTarget.id);
});
inner.addEventListener("mouseout", function () {
  console.log("Leave" + event.target.id + "Enter" + event.relatedTarget.id);
});
inner.addEventListener("mouseleave", function () {
  console.log("Leave" + event.target.id + "Enter" + event.relatedTarget.id);
});

// The mouse enters the inner from outer and outputs
// Enter inner and leave outer
// Enter inner and leave outer

// The mouse enters the outer from the inner and outputs
// leave inner and enter outer
// leave inner and enter outer

Instance method of MouseEvent interface

MouseEvent.getModifierState()

The MouseEvent.getModifierState method returns a boolean value indicating whether a specific function key has been pressed. Its parameter is a string representing function key.

document.addEventListener(
  "click",
  function (e) {
    console.log(e.getModifierState("CapsLock"));
  },
  false
);

The above code can know whether the user has pressed the uppercase key.

WheelEvent interface

Overview

The WheelEvent interface inherits the MouseEvent instance, which represents the instance object of the mouse wheel event. Currently, there is only one wheel event related to the mouse wheel. When the user rolls the mouse wheel, an instance of this event is generated.

The browser natively provides the WheelEvent() constructor to generate the WheelEvent instance.

var wheelEvent = new WheelEvent(type, options);

The WheelEvent() constructor can accept two parameters. The first is a string, which represents the event type. For the wheel event, this value can only be wheel at present. The second parameter is the configuration object of the event. In addition to the configuration properties of Event and UIEvent, the properties of this object can also accept the following properties, all of which are optional.

-deltaX: Numerical value, indicating the amount of horizontal scrolling of the wheel, the default value is 0.0. -deltaY: Numeric value, indicating the amount of vertical scrolling of the scroll wheel, the default value is 0.0. -deltaZ: Numerical value, representing the scrolling amount of the wheel on the Z axis, the default value is 0.0. -deltaMode: numeric value, indicating the unit of the related scroll event, applicable to the above three attributes. 0 means the scroll unit is pixel, 1 means the unit is line, 2 means the unit is page, the default is 0.

Instance attributes

In addition to the instance properties and instance methods of Event and MouseEvent, the WheelEvent event instance also has some of its own instance properties, but it does not have its own instance methods.

The following attributes are read-only attributes.

-WheelEvent.deltaX: Numerical value, indicating the amount of horizontal scrolling of the wheel. -WheelEvent.deltaY: Numerical value, indicating the amount of vertical scrolling of the wheel. -WheelEvent.deltaZ: Numerical value, indicating the scrolling amount of the wheel on the Z axis. -WheelEvent.deltaMode: numeric value, representing the unit of the above three attributes, 0 is pixel, 1 is line, and 2 is page.