Mouse, Keyboard and Pointer Events

Updated · 8 min read
mediumES2026javascripteventskeyboardpointer-eventsaccessibility

Input events report what people do with their mouse, finger, pen and keyboard. Modern browsers provide pointer events, one unified set of events for mouse, touch and pen, alongside the classic mouse events, plus keyboard events that tell you exactly which key was pressed through event.key. Handling input well also means handling it accessibly: anything that can be clicked must also work from the keyboard, which native elements like <button> do for you.

In One Minute

  • click fires for mouse clicks, taps, and pressing Enter or Space on a focused button: it is the most accessible event.
  • Pointer events (pointerdown, pointermove, pointerup) cover mouse, touch and pen with one API; event.pointerType says which.
  • Keyboard: keydown and keyup. Read event.key ("Enter", "Escape", "a") for meaning, event.code ("KeyA") for physical position.
  • Modifier keys: event.shiftKey, ctrlKey, altKey, metaKey.
  • Focus: focus/blur (don't bubble) and focusin/focusout (do); element.focus() moves focus.

Mouse and Click Events

EventFires when
clickPressed and released on the same element (also keyboard activation of buttons and links)
dblclickTwo clicks in quick succession
contextmenuRight click or long press (before the menu opens)
mousedown / mouseupA mouse button goes down / up
mouseover / mouseoutThe pointer enters or leaves an element or its children (bubble)
mouseenter / mouseleaveThe pointer enters or leaves the element itself (don't bubble)
mousemoveThe pointer moves over the element
mouse.html
<div id="box" style="width:120px;height:60px;background:#eee">Click me</div>
<script>
  const box = document.querySelector("#box");
  for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
    box.addEventListener(type, (e) => console.log(type, "button", e.button));
  }
</script>
Output
pointerdown button 0
mousedown button 0
pointerup button 0
mouseup button 0
click button 0

A single mouse click produces this sequence: pointer events first, then the compatible mouse events, then click. event.button is 0 for the main (left) button, 1 for the middle and 2 for the right. Coordinates are in clientX/clientY (relative to the viewport), pageX/pageY (relative to the document) and offsetX/offsetY (relative to the element).

Pointer Events

Pointer events are the modern replacement for separate mouse and touch events. The same code handles a mouse, a finger or a stylus:

PropertyMeaning
event.pointerType"mouse", "touch" or "pen"
event.pointerIdIdentifies each pointer (each finger in multi-touch)
event.pressurePen or touch pressure, 0 to 1
event.isPrimarytrue for the first finger or the mouse

For dragging, element.setPointerCapture(event.pointerId) keeps sending that pointer's events to the element even when the pointer moves outside it. On touch screens, add the CSS touch-action: none to an element that handles its own dragging, so the browser doesn't scroll instead.

pointer.html
<div id="pad" style="width:100px;height:100px;touch-action:none">Pad</div>
<script>
  document.querySelector("#pad").addEventListener("pointerdown", (event) => {
    console.log(event.pointerType, event.isPrimary, event.pointerId > 0);
  });
</script>
Output
mouse true true

Keyboard Events

EventFires when
keydownA key is pressed (repeats while held; check event.repeat)
keyupA key is released
keypressDeprecated; don't use
PropertyMeaningExample values
event.keyThe character or meaning of the key, taking layout and Shift into account"a", "A", "Enter", "Escape", "ArrowDown", " " (Space)
event.codeThe physical key position, the same on every layout"KeyA", "Enter", "Space", "ArrowDown"
event.shiftKey, ctrlKey, altKey, metaKeyWhether modifier keys were heldtrue / false
event.repeattrue for auto-repeat while held down
keyboard.html
<input id="search">
<script>
  document.querySelector("#search").addEventListener("keydown", (event) => {
    console.log(`key=${event.key} code=${event.code} shift=${event.shiftKey}`);
    if (event.key === "Enter") console.log("Search submitted");
    if (event.key === "Escape") event.currentTarget.value = "";
  });
</script>
Output
key=a code=KeyA shift=false
key=Shift code=ShiftLeft shift=true
key=A code=KeyA shift=true
key=Enter code=Enter shift=false
Search submitted
key=Escape code=Escape shift=false

Explanation: pressing Shift+A produced two keydown events: one for Shift itself and one for A, whose key is the capital "A" because Shift was held. Use event.key for meaning ("the user typed A", "the user pressed Escape"); use event.code only for position-based controls, such as games using WASD, which must stay in the same place on a French or German keyboard.

Keyboard Shortcuts

shortcut.html
<p>Press Ctrl+S to save</p>
<script>
  document.addEventListener("keydown", (event) => {
    const saveCombo = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s";
    if (!saveCombo) return;
    event.preventDefault();
    console.log("Saved the Fee Tracker");
  });
</script>
Output
Saved the Fee Tracker

Checking ctrlKey || metaKey supports both Windows and Linux (Ctrl) and macOS (Cmd, reported as metaKey). preventDefault() stops the browser's own "Save page" dialog. Don't override shortcuts that people rely on, like Ctrl+F or Ctrl+C, and avoid single-letter shortcuts that fire while someone types in a field.

Focus Events

Focus is the element that receives keyboard input. People move it with Tab and Shift+Tab, by clicking, or your code moves it with element.focus():

focus.html
<input id="amount" placeholder="Amount">
<input id="note" placeholder="Note">
<script>
  const amount = document.querySelector("#amount");
  amount.addEventListener("focus", () => console.log("amount focused"));
  amount.addEventListener("blur", () => console.log("amount lost focus, value:", JSON.stringify(amount.value)));
  document.addEventListener("focusin", (e) => console.log("focusin:", e.target.id));
</script>
Output
amount focused
focusin: amount
amount lost focus, value: ""
focusin: note

focus and blur don't bubble; focusin and focusout do, so a single listener on a form or the document can track focus for every field. document.activeElement always tells you which element has focus.

Accessible Custom Controls

The best way to make something clickable is to use a <button>. It is focusable with Tab, fires click on Enter and Space, and is announced as a button by screen readers. A <div> with a click listener does none of that:

accessible.html
<button id="real" type="button">Real button</button>
<div id="fake">Div pretending</div>
<div id="fixed" role="button" tabindex="0">Div repaired</div>
<script>
  const say = (e) => console.log("activated:", e.currentTarget.id);
  document.querySelector("#real").addEventListener("click", say);
  document.querySelector("#fake").addEventListener("click", say);

  const fixed = document.querySelector("#fixed");
  fixed.addEventListener("click", say);
  fixed.addEventListener("keydown", (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      fixed.click();
    }
  });
</script>
Output
activated: real
activated: real
activated: fixed

Explanation: pressing Enter on the real button fired click automatically. Then the checker tried to focus the plain <div> and press Enter, but a <div> can't receive focus, so focus stayed on the real button, and Enter activated it a second time. A keyboard user can never reach the fake button at all. Repairing it takes three additions: tabindex="0" (focusable), role="button" (announced correctly), and a keydown handler for Enter and Space. Using <button> gets all of this for free.

In Practice

The Fee Tracker's list of students supports keyboard navigation: Up and Down arrows move focus between rows, Enter opens the selected student, and Escape returns focus to the search box:

keyboard-list.html
<input id="search">
<ul id="students">
  <li id="s1" tabindex="0">Navika</li>
  <li id="s2" tabindex="-1">Srihitha</li>
  <li id="s3" tabindex="-1">Advitha</li>
</ul>
<script>
  const list = document.querySelector("#students");
  list.addEventListener("keydown", (event) => {
    const current = event.target.closest("li");
    if (!current) return;
    const moves = { ArrowDown: current.nextElementSibling, ArrowUp: current.previousElementSibling };
    if (event.key in moves && moves[event.key]) {
      event.preventDefault();
      moves[event.key].focus();
      console.log("focus:", document.activeElement.textContent);
    } else if (event.key === "Enter") {
      console.log("open:", current.textContent);
    } else if (event.key === "Escape") {
      document.querySelector("#search").focus();
      console.log("back to:", document.activeElement.id);
    }
  });
</script>
Output
focus: Srihitha
focus: Advitha
open: Advitha
back to: search

tabindex="0" puts the first item in the Tab order; tabindex="-1" makes the others focusable from code without adding every row to the Tab sequence (a pattern called a roving focus).

Common Mistakes

Using mousedown or pointerdown for activation. Keyboard and assistive technology users can't trigger them. Use click.

Clickable <div>s. Use <button>, or add tabindex, role and keyboard handling.

Using keyCode. Deprecated. Use event.key.

Reading typed text from key events. Use the input event, which also catches paste, autocomplete and voice typing.

Practice

Challenge: Close a "dialog" <div> when Escape is pressed anywhere on the page, logging "dialog closed" once, and ignore all other keys.

Show solution
escape.html
<div id="dialog">Payment details</div>
<script>
  document.addEventListener("keydown", (event) => {
    const dialog = document.querySelector("#dialog");
    if (event.key !== "Escape" || dialog.hidden) return;
    dialog.hidden = true;
    console.log("dialog closed");
  });
</script>
Output
dialog closed

Quick check: Input events

3 questions
1Which event fires for a mouse click, a tap, and Enter on a focused button?
2What is event.key when Shift+A is pressed?
3Which events bubble and can be delegated to a form?

Key Takeaways

NeedUse
Activationclick
Drawing or draggingpointerdown / pointermove / pointerup
A specific keyevent.key === "Escape"
Shortcut(e.ctrlKey || e.metaKey) && e.key === "s"
Track focus in a formform.addEventListener("focusin", ...)

Was this tutorial helpful?

Lesson 75 of 139