Keyboard & Mouse Events0%
Keyboard & Mouse Events
Beginner12 min read•Updated: Jul 11, 2026
Keyboard & Mouse Events in Modern JavaScript
Capturing user input through keyboards, mice, and pointer devices is essential for creating interactive web apps like search dropdowns, modal windows, drag-and-drop interfaces, and gaming loops.
1. Keyboard Events: keydown, keyup, and key
Event Types
keydown: Fires immediately when a key is pressed down. Repeats if held down.keyup: Fires when the key is released.- (Note:
keypressis deprecated and should not be used in modern code).
Key Properties: key vs. code
JavaScript
window.addEventListener('keydown', (event) => {
console.log('Key:', event.key); // Actual character printed (e.g. 'Enter', 'a', 'A', 'Escape')
console.log('Code:', event.code); // Physical hardware key code (e.g. 'KeyA', 'Enter', 'Space')
console.log('Modifier keys:', {
ctrl: event.ctrlKey,
alt: event.altKey,
shift: event.shiftKey,
meta: event.metaKey // Command on Mac, Windows key on PC
});
});
Output
Physical Keyboard Key: [ 'A' key ]
• When Shift is NOT pressed: key = 'a', code = 'KeyA'
• When Shift IS pressed: key = 'A', code = 'KeyA'
Implementing Keyboard Shortcuts (Modal Escape)
JavaScript
document.addEventListener('keydown', (event) => {
// Close modal on 'Escape'
if (event.key === 'Escape') {
const activeModal = document.querySelector('.modal.open');
if (activeModal) activeModal.classList.remove('open');
}
// Save shortcut: Ctrl + S or Cmd + S
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
event.preventDefault(); // Prevent browser 'Save Webpage' dialog
saveDocument();
}
});
2. Mouse Events: click, dblclick, mousedown, mouseup
JavaScript
const box = document.querySelector('.interactive-box');
box.addEventListener('mousedown', (e) => {
// e.button: 0 = Main (Left), 1 = Auxiliary (Middle), 2 = Secondary (Right)
if (e.button === 0) {
console.log('Left mouse button pressed');
}
});
box.addEventListener('contextmenu', (e) => {
e.preventDefault(); // Prevents default browser right-click menu
showCustomContextMenu(e.clientX, e.clientY);
});
3. Mouse Coordinate Systems: client, page, and screen
Output
┌──────────────────────────────────────────────┐ Screen (e.screenX/Y)
│ Monitor Display Boundary │
│ ┌────────────────────────────────────────┐ │
│ │ Browser Window Viewport │ │ Client (e.clientX/Y)
│ │ (e.clientX = relative to viewport) │ │
│ │ ┌──────────────────────────────────┐ │ │
│ │ │ Rendered Web Page Document │ │ │ Page (e.pageX/Y)
│ │ │ (e.pageX = includes scroll offset│ │ │
│ │ └──────────────────────────────────┘ │ │
│ └────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘
JavaScript
document.addEventListener('mousemove', (e) => {
// Coordinates relative to visible viewport window
const clientX = e.clientX;
const clientY = e.clientY;
// Coordinates relative to whole HTML document (includes scroll position)
const pageX = e.pageX;
const pageY = e.pageY;
// Update a custom cursor position
customCursor.style.transform = `translate3d(${clientX}px, ${clientY}px, 0)`;
});
4. mouseenter / mouseleave vs. mouseover / mouseout
This difference is critical for hover menus and tooltips:
mouseoverandmouseout: Bubble up through child elements. Moving over a child inside the container fires additional events!mouseenterandmouseleave: Do NOT bubble. They trigger strictly when entering or leaving the target element boundary.
JavaScript
const dropdown = document.querySelector('.dropdown');
// Clean hover behavior without child flickering
dropdown.addEventListener('mouseenter', () => dropdown.classList.add('active'));
dropdown.addEventListener('mouseleave', () => dropdown.classList.remove('active'));
5. Pointer Events: The Modern Unified Standard
Pointer Events unify Mouse, Touch, and Stylus/Pen interactions into a single API:
JavaScript
const canvas = document.querySelector('#drawing-canvas');
canvas.addEventListener('pointerdown', (e) => {
console.log(`Input Device: ${e.pointerType}`); // 'mouse', 'touch', or 'pen'
console.log(`Pressure: ${e.pressure}`); // Stylus pressure level (0.0 to 1.0)
});
Interactive Quiz
Practice Quiz
Question 1
Which property should you check to inspect the actual semantic character generated by a key press?
Question 2
How do mouseenter and mouseleave differ from mouseover and mouseout?
Question 3
What coordinate property represents mouse position relative to the visible browser viewport?
Question 4
How do you prevent the standard browser context menu from appearing upon right-click?
Question 5
What is the main advantage of the Pointer Events API (pointerdown, pointermove) over traditional Mouse Events?
Next Lesson
Form Events and Validation
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Event Bubbling & Capturing | Form Events and Validation |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.