views:

48

answers:

2

So, that's the question =)

How to capture mac's command key via javascript?

+1  A: 
var element = //the DOM element to listen for the key on.
element.onkeyup = function(e) {
   if(e.metaKey) {
      //command key was pressed
   }
}
Jacob Relkin
Does not work :(
DataGreed
@DataGreed, show me your code please.
Jacob Relkin
Is meta key same as the Mac `Command`?
Nivas
var element = document.body; element.onKeyUp = function(e) { if(e.metaKey) { console.log('cmd pressed') }}
DataGreed
+3  A: 

Unlike Shift/Alt/Ctrl, Mac/Apple key is not considered as a modifier key--instead, you should hook on keydown/keyup and record when a key is pressed and then depressed based on event.keyCode.

Unfortunately, these key codes are browser-dependent:

Firefox: 224
Opera: 17
WebKit (Safari/Chrome): 91 (Left Apple) or 93 (Right Apple)

You might be interested in reading this article: JavaScript Madness: Keyboard Events from which I mastered that knowledge.

Ilya Semenov
Wow, that's what I wanted to hear. Spasibo, Ilya ;)
DataGreed