-1

I Have some Function . For example

<script>

//Function1
alert('Function 1 run')

//Function2
alert('Function 2 run')

</script>

i need this functions run with .keypress jQuery , for example press special key 1 + special key 2 like Ctrl + Character

<script>

('html').on('keypress' , ' Ctrl + A ' , function () {

     alert('Function 1 run')

});

('html').on('keypress' , ' Ctrl + B ' , function () {

     alert('Function 2 run')

});

</script>

so what would u guys suggest me ?

Danin Na
  • 409
  • 1
  • 3
  • 13
  • did you try `$(document).on('keypress ...` – joyBlanks Aug 17 '15 at 10:26
  • **[Link](http://stackoverflow.com/questions/2767126/how-to-detect-that-ctrlr-was-pressed)**, **[Link](http://stackoverflow.com/questions/2903991/how-to-detect-ctrlv-ctrlc-using-javascript)** and **[Link](http://stackoverflow.com/questions/9374915/javascript-detect-ctrl-key-pressed-or-up-keypress-event-doest-trigger)**. – Tahir Ahmed Aug 17 '15 at 10:31
  • You can use the jquery plugin as hotkeys.js – Umesh Sehta Aug 17 '15 at 10:32
  • `keypress` doesn't work with non-printing keys such as Ctrl. You have to use `keydown/keyup` instead – hindmost Aug 17 '15 at 10:32

2 Answers2

1

Event keydown will catch the Ctrl press and it is being held the value will be true. Eventhough this works, I think it is better to use some plugins for this, because there are many browser compatibility issues might come up.

$(document).on('keydown',function(event){
   if(event.ctrlKey && (event.which == 65)){
      alert('Ctrl+A');
     event.preventDefault();
   }
   if(event.ctrlKey && (event.which == 66)){
      alert('Ctrl+B');
     event.preventDefault();
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
rrk
  • 15,677
  • 4
  • 29
  • 45
1

Just try this,

$(document).keypress(function(e) {
    if(e.ctrlKey && e.key == "a") {
        alert('function 1');
    }
    if(e.ctrlKey && e.key == "b") {
        alert('function 2');
    }
});
Sathish
  • 2,440
  • 1
  • 11
  • 27