Detect modifier keys on button click eveent

I want to take different actions on a button click event if modifier keys are pressed (ALT or CTRL on Windows). Is this possible in UXP?

This can be achieved with the following code.

const handleClick = (event) => {
  if(event.altKey) {
    console.log('altKey') ;
  }

  if(event.ctrlKey) {
    console.log('ctrlKey') ;
  }
} ;

However, there was some caveats at the time I tried it. Not sure now.

  • You need to use sp-button instead of button element.
  • ctrlKey acquisition is unstable on Windows.

Thanks, this is working as desired. Is this documented somewhere I should have been able to find? If not, please provide equivalent values for Mac

This is a good place to check general web development documentation, not just UXP. For example Element: click event - Web APIs | MDN.

For macOS, it is equivalent to write like this.

const handleClick = (event) => {
  if(event.altKey) {
    console.log('option key') ;
  }

  if(event.metaKey) {
    console.log('command key') ;
  }
} ;