MouseEvent.getModifierState() Sample

Available in Chrome 47+ | View on GitHub | Browse Samples

Background

The MouseEvent.getModifierState() method returns information about which modifier keys were pressed at the time a MouseEvent was fired.

While the demo below illustrates its use with the mousemove event, any event that uses the MouseEvent interface supports getModifierState().

Live Output

Move your mouse within this area while pressing one or more keyboard modifier keys.

The keys you have pressed will appear in bold.


JavaScript Snippet

// A subset of keys from https://w3c.github.io/uievents/#keys-modifiers
var modifierKeys = ['Alt', 'Control', 'Meta', 'Shift', 'AltGraph'];

document.querySelector('#output').addEventListener('mousemove', function(evt) {
  modifierKeys.forEach(function(modifierKey) {
    var pressed = evt.getModifierState(modifierKey);
    document.getElementById(modifierKey).style.fontWeight =
      pressed ? 'bold' : 'normal';
  });
});