Mouse, Keyboard and Pointer Events
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
clickfires 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.pointerTypesays which. - Keyboard:
keydownandkeyup. Readevent.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) andfocusin/focusout(do);element.focus()moves focus.
Mouse and Click Events
| Event | Fires when |
|---|---|
click | Pressed and released on the same element (also keyboard activation of buttons and links) |
dblclick | Two clicks in quick succession |
contextmenu | Right click or long press (before the menu opens) |
mousedown / mouseup | A mouse button goes down / up |
mouseover / mouseout | The pointer enters or leaves an element or its children (bubble) |
mouseenter / mouseleave | The pointer enters or leaves the element itself (don't bubble) |
mousemove | The pointer moves over the element |
<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>pointerdown button 0
mousedown button 0
pointerup button 0
mouseup button 0
click button 0A 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:
| Property | Meaning |
|---|---|
event.pointerType | "mouse", "touch" or "pen" |
event.pointerId | Identifies each pointer (each finger in multi-touch) |
event.pressure | Pen or touch pressure, 0 to 1 |
event.isPrimary | true 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.
<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>mouse true trueKeyboard Events
| Event | Fires when |
|---|---|
keydown | A key is pressed (repeats while held; check event.repeat) |
keyup | A key is released |
keypress | Deprecated; don't use |
| Property | Meaning | Example values |
|---|---|---|
event.key | The character or meaning of the key, taking layout and Shift into account | "a", "A", "Enter", "Escape", "ArrowDown", " " (Space) |
event.code | The physical key position, the same on every layout | "KeyA", "Enter", "Space", "ArrowDown" |
event.shiftKey, ctrlKey, altKey, metaKey | Whether modifier keys were held | true / false |
event.repeat | true for auto-repeat while held down |
<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>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=falseExplanation: 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
<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>Saved the Fee TrackerChecking 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():
<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>amount focused
focusin: amount
amount lost focus, value: ""
focusin: notefocus 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:
<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>activated: real
activated: real
activated: fixedExplanation: 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:
<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>focus: Srihitha
focus: Advitha
open: Advitha
back to: searchtabindex="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
<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>dialog closedKey Takeaways
| Need | Use |
|---|---|
| Activation | click |
| Drawing or dragging | pointerdown / pointermove / pointerup |
| A specific key | event.key === "Escape" |
| Shortcut | (e.ctrlKey || e.metaKey) && e.key === "s" |
| Track focus in a form | form.addEventListener("focusin", ...) |
Was this tutorial helpful?