Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

MouseEvent: button code and viewport coordinates

Use `button` to identify the button pressed or released in a mouse event, and `clientX` and `clientY` to read where the event occurred in the viewport.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

event.button
 event.clientX
 event.clientY

new MouseEvent(type, { button, buttons, clientX, clientY })

MouseEvent.button/clientX/clientY groups three read-only instance properties. In a handler, read event.button, not MouseEvent.button. MouseEvent is a Web API, not part of ECMAScript 2024. In a runtime without the constructor, new MouseEvent(...) throws a ReferenceError if the name is not defined.

For events such as mousedown and mouseup, button identifies which button was pressed or released: 0 primary (usually left), 1 auxiliary (usually middle), 2 secondary (usually right), 3 fourth (usually Back), and 4 fifth (usually Forward). These are logical roles, not fixed physical positions. On mousemove, button === 0 does not prove the primary button is held. To check held buttons, use the buttons bitmask: 0 means none, and (event.buttons & 1) !== 0 tests the primary button.

clientX and clientY are the event's horizontal and vertical coordinates, respectively, in CSS pixels. The viewport's top-left corner is (0, 0); X increases to the right and Y downward. Scrolling leaves that origin in place but can change the client coordinates of the same document point in a later event. pageX and pageY are relative to the document, screenX and screenY to the screen, and client coordinates are not local to the target element.

Use new MouseEvent(type, options) to set initial values on a synthetic event. Creating the object neither dispatches the event nor moves the pointer. The event has isTrusted === false and does not grant user activation.

Examples

<!doctype html>
<meta charset="utf-8">
<title>MouseEvent example</title>
<pre id="output"></pre>
<script>
  {
    const event = new MouseEvent("mouseup", {
      button: 2,
      buttons: 0,
      clientX: 120,
      clientY: 45,
    });

    document.getElementById("output").textContent =
      `button=${event.button}, buttons=${event.buttons}, clientX=${event.clientX}, clientY=${event.clientY}`;
  }
</script>

Result

button=2, buttons=0, clientX=120, clientY=45

Save the example as an HTML file and open it in a browser. The synthetic `mouseup` describes a secondary-button release at `(120, 45)`; `buttons=0` means no buttons remain held. No click is needed.

Related lessons

  • JavaScript · Lesson 35 · Intermediate · Version: 3

Sources