jquery : how to use keyboard shortcut F2 and F3
Asked Answered
N

3

5

Good day,

Im wondering if we can use keyboard shortcut F2 and F3 to execute function. If got, maybe can share your code to me. Below my idea to make the shortcut key. i've tried but not functioning.

$("#ENQUIRY_VIEWMETER").keypress(function(event) {
    if(event.which == 113) { //F2
        updateMtr();
    } else if(event.which == 114) { //F3
        resetView();
    }
});

p/s : or maybe need some amendment on my code. :)

Noakes answered 5/7, 2012 at 6:50 Comment(1)
search before post keyboard-shortcuts-with-jquerySubsume
K
12

Try using the keydown event instead of keypress. The keydown event tells you which actual key was pressed, but keypress is more about what character resulted.

And return false so that the default browser behaviour (if any) for those keys doesn't go ahead (don't return false for other keys).

$("#ENQUIRY_VIEWMETER").keydown(function(event) {
    if(event.which == 113) { //F2
        updateMtr();
        return false;
    }
    else if(event.which == 114) { //F3
        resetView();
        return false;
    }
});

Demo: http://jsfiddle.net/TTrPp/

Klina answered 5/7, 2012 at 6:55 Comment(1)
Got it!!.. i knew it, its not that hard.. thx for the answer!!Noakes
S
2

try like this

$(document).keypress(function(e){
   if(e.charCode == 97){
      alert("a");
      return false;
  }
 })

check this jQuery HotKey plugin

Subsume answered 5/7, 2012 at 6:55 Comment(1)
OP wants to know how to test for function keys. keypress is the wrong way to do that (otherwise the code in the question would work).Klina
P
0
document.onkeyup = KeyCheck;

function KeyCheck(e){

   var KeyID = (window.event) ? event.keyCode : e.keyCode;

   if(KeyID == 113){ 

      updateMtr();

   } else if(KeyID == 114) {

       resetView();
    }
}
Publia answered 8/10, 2021 at 6:31 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Curvature
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂Assort

© 2022 - 2024 — McMap. All rights reserved.