Course contentsShow
← Web Development
Lesson 752 of 2,98213. DOM EventsFree lesson

Modifier Keys: shiftKey, ctrlKey, altKey, and metaKey

Detecting whether modifier keys were held during mouse or keyboard events.

Modifier Keys: shiftKey, ctrlKey, altKey, and metaKey

You'll learn how to detect whether Shift, Ctrl, Alt, or Command/Meta keys were held down during mouse or keyboard events.

What Are Modifier Keys?

Modifier keys are special keys that don't trigger actions by themselves—they modify the behavior of other keys or mouse actions. Think of them like seasoning: pressing "S" types a letter, but holding Shift while pressing "S" gives you a capital "S". In web applications, detecting these keys lets you create powerful shortcuts like Ctrl+S to save or Shift+Click to select multiple items.

The Four Modifier Properties

Every mouse and keyboard event object includes four boolean properties that tell you which modifier keys were pressed:

  • event.shiftKey – true if Shift was held
  • event.ctrlKey – true if Ctrl (Control) was held
  • event.altKey – true if Alt (Option on Mac) was held
  • event.metaKey – true if Meta (Command on Mac, Windows key on PC) was held

Checking Modifier Keys

document.addEventListener('click', function(event) {
  if (event.shiftKey) {
    console.log('Shift + Click detected!');
  }
  
  if (event.ctrlKey) {
    console.log('Ctrl + Click detected!');
  }
});

document.addEventListener('keydown', function(event) {
  if (event.key === 's' && event.ctrlKey) {
    event.preventDefault(); // Stop default browser save
    console.log('Custom save triggered!');
  }
});

Combining Modifiers

You can check multiple modifiers together to create complex shortcuts:

document.addEventListener('keydown', function(event) {
  if (event.key === 'z' && event.ctrlKey && event.shiftKey) {
    console.log('Redo action (Ctrl+Shift+Z)');
  }
});

Key Takeaway: The shiftKey, ctrlKey, altKey, and metaKey properties on event objects let you detect modifier keys during any mouse or keyboard interaction, enabling keyboard shortcuts and enhanced user interactions.