Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect command key is pressed in javascript at mac os

Tags:

javascript

I am working with ctrl+c and ctrl+v event in javascript i want to bind a function on ctrl+v event. and i am able to do it with event.keyCode in windows system but in mac os on command press i am not able to figure out the event. My code is

 $('.hindi_content').keyup(function(event){

        console.log('UP'+event.keyCode);

       console.log('in window::'+ event.ctrlKey+'in mac os'+event.metaKey+'####'+event.META_MASK+'##$&&'+event.CTRL_MASK);

      //  this is  working with windows not with mac os. 
       if(event.keyCode==86 && event.ctrlKey)
        {
            console.log('ctrl press'+event.ctrlKey);

            col_val = $('#'+this.id).val();
            console.log('col val'+col_val);

            $('#hidden_'+this.id).val(col_val);
            console.log('hidden val'+ $('#hidden_'+this.id).val());
            //converter_new(event,this.lang);
            // return;
        } 

});

i search and found event.metaKey but it is for ctrl key in mac i just want command key in mac os.

like image 679
Sandy Jain Avatar asked Aug 22 '13 06:08

Sandy Jain


People also ask

How do I know if my Command key is working Mac?

Open up System Preferences -> Keyboard and click the Keyboard tab. At the bottom of this window a "Modifier Keys". Click this button and check that the command key is set to the command key.

What is Command key in Mac OS?

The Command key is the most common modifier key in Mac OS X. Many menu items, such as Quit, Close, and Save, have a keystroke shortcut using the Command key. To use such a shortcut, hold down one of the Command keys and press the letter key for that item.

Where is the Command key on my Mac?

You'll find the Command key next to the Space bar. There is one on either side.


2 Answers

Things seem to have gotten easier since this question was first asked. I found this answer which states that event.metaKey will work for cmd on mac. I just tested it and it works fine.

document.body.addEventListener("keydown", function(event) {
   var key = event.key;
   var cmd_held = event.metaKey;

   if(cmd_held && key.toLowerCase() == "v") 
       pasta();

});
like image 55
Seph Reed Avatar answered Oct 24 '22 06:10

Seph Reed


mousetrap is a library that makes those things really easy:

http://craig.is/killing/mice

//control + v
Mousetrap.bind('ctrl+v', function(e) {
    //do things here
});

//command + k & control +v
Mousetrap.bind(['command+v', 'ctrl+v'], function(e) {
    //do things here
});
like image 22
mgherkins Avatar answered Oct 24 '22 06:10

mgherkins