[javascript] Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

I want to handle F1-F12 keys using JavaScript and jQuery.

I am not sure what pitfalls there are to avoid, and I am not currently able to test implementations in any other browsers than Internet Explorer 8, Google Chrome and Mozilla FireFox 3.

Any suggestions to a full cross-browser solution? Something like a well-tested jQuery library or maybe just vanilla jQuery/JavaScript?

This question is related to javascript jquery events keyboard keyboard-events

The answer is


One of the problems in trapping the F1-F12 keys is that the default function must also be overridden. Here is an example of an implementation of the F1 'Help' key, with the override that prevents the default help pop-up. This solution can be extended for the F2-F12 keys. Also, this example purposely does not capture combination keys, but this can be altered as well.

<html>
<head>
<!-- Note:  reference your JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <h1>F-key trap example</h1>
    <div><h2>Example:  Press the 'F1' key to open help</h2></div>
    <script type="text/javascript">
        //uncomment to prevent on startup
        //removeDefaultFunction();          
        /** Prevents the default function such as the help pop-up **/
        function removeDefaultFunction()
        {
            window.onhelp = function () { return false; }
        }
        /** use keydown event and trap only the F-key, 
            but not combinations with SHIFT/CTRL/ALT **/
        $(window).bind('keydown', function(e) {
            //This is the F1 key code, but NOT with SHIFT/CTRL/ALT
            var keyCode = e.keyCode || e.which;
            if((keyCode == 112 || e.key == 'F1') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Open help window here instead of alert
                alert('F1 Help key opened, ' + keyCode);
                }
            // Add other F-keys here:
            else if((keyCode == 113 || e.key == 'F2') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Do something else for F2
                alert('F2 key opened, ' + keyCode);
                }
        });
    </script>
</body>
</html>

I borrowed a similar solution from a related SO article in developing this. Let me know if this worked for you as well.


You can do this with jquery like this:

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });

I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.


This works for me.

if(code ==112) { alert("F1 was pressed!!"); return false; }

F2 - 113, F3 - 114, F4 - 115, and so fort.


When you use angular.js for handling events, you should use ng-keydown for preventing pause in developer in chrome.


I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.


Solution in ES6 for modern browsers and IE11 (with transpilation to ES5):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the shortcut library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way.

Single keystroke:

shortcut.add("F1", function() {
    alert("F1 pressed");
});

Combination of keystrokes:

shortcut.add("Ctrl+Shift+A", function() {
    alert("Ctrl Shift A pressed");
});

This works for me.

if(code ==112) { alert("F1 was pressed!!"); return false; }

F2 - 113, F3 - 114, F4 - 115, and so fort.


I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the shortcut library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way.

Single keystroke:

shortcut.add("F1", function() {
    alert("F1 pressed");
});

Combination of keystrokes:

shortcut.add("Ctrl+Shift+A", function() {
    alert("Ctrl Shift A pressed");
});

Without other external class you can create your personal hack code simply using

event.keyCode

Another help for all, I think is this test page for intercept the keyCode (simply copy and past in new file.html for testing your event).

 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 <style type="text/css">
 td,th{border:2px solid #aaa;}
 </style>
 <script type="text/javascript">
 var t_cel,tc_ln;
 if(document.addEventListener){ //code for Moz
   document.addEventListener("keydown",keyCapt,false); 
   document.addEventListener("keyup",keyCapt,false);
   document.addEventListener("keypress",keyCapt,false);
 }else{
   document.attachEvent("onkeydown",keyCapt); //code for IE
   document.attachEvent("onkeyup",keyCapt); 
   document.attachEvent("onkeypress",keyCapt); 
 }
 function keyCapt(e){
   if(typeof window.event!="undefined"){
    e=window.event;//code for IE
   }
   if(e.type=="keydown"){
    t_cel[0].innerHTML=e.keyCode;
    t_cel[3].innerHTML=e.charCode;
   }else if(e.type=="keyup"){
    t_cel[1].innerHTML=e.keyCode;
    t_cel[4].innerHTML=e.charCode;
   }else if(e.type=="keypress"){
    t_cel[2].innerHTML=e.keyCode;
    t_cel[5].innerHTML=e.charCode;
   }
 }
 window.onload=function(){
   t_cel=document.getElementById("tblOne").getElementsByTagName("td");
   tc_ln=t_cel.length;
 }
 </script>
 </head>
 <body>
 <table id="tblOne">
 <tr>
 <th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
 </tr>
 <tr>
 <th>keyCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 <tr>
 <th>charCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 </table>
 <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
 </body>
 </html>

Here is a working demo so you can try it right here:

_x000D_
_x000D_
var t_cel, tc_ln;_x000D_
if (document.addEventListener) { //code for Moz_x000D_
  document.addEventListener("keydown", keyCapt, false);_x000D_
  document.addEventListener("keyup", keyCapt, false);_x000D_
  document.addEventListener("keypress", keyCapt, false);_x000D_
} else {_x000D_
  document.attachEvent("onkeydown", keyCapt); //code for IE_x000D_
  document.attachEvent("onkeyup", keyCapt);_x000D_
  document.attachEvent("onkeypress", keyCapt);_x000D_
}_x000D_
_x000D_
function keyCapt(e) {_x000D_
  if (typeof window.event != "undefined") {_x000D_
    e = window.event; //code for IE_x000D_
  }_x000D_
  if (e.type == "keydown") {_x000D_
    t_cel[0].innerHTML = e.keyCode;_x000D_
    t_cel[3].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keyup") {_x000D_
    t_cel[1].innerHTML = e.keyCode;_x000D_
    t_cel[4].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keypress") {_x000D_
    t_cel[2].innerHTML = e.keyCode;_x000D_
    t_cel[5].innerHTML = e.charCode;_x000D_
  }_x000D_
}_x000D_
window.onload = function() {_x000D_
  t_cel = document.getElementById("tblOne").getElementsByTagName("td");_x000D_
  tc_ln = t_cel.length;_x000D_
}
_x000D_
td,_x000D_
th {_x000D_
  border: 2px solid #aaa;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Untitled</title>_x000D_
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table id="tblOne">_x000D_
    <tr>_x000D_
      <th style="border:none;"></th>_x000D_
      <th>onkeydown</th>_x000D_
      <th>onkeyup</th>_x000D_
      <th>onkeypress</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>keyCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>charCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.


Add a shortcut:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

Start reacting to shortcuts:

$.Shortcuts.start();

Add a shortcut to “another” list:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

Activate “another” list:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

Stop (unbind event handlers):

$.Shortcuts.stop();


Tutorial:
http://www.stepanreznikov.com/js-shortcuts/


When you use angular.js for handling events, you should use ng-keydown for preventing pause in developer in chrome.


My solution to this problem is:

document.onkeypress = function (event) {
    event = (event || window.event);
    if (event.keyCode == 123) { 
         return false;
    }
}

With the magic number 123 which is the key F12.


Wow it is very simple. i'm blame to write this, why no one make it before?

$(function(){
    //Yes! use keydown 'cus some keys is fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well you need keep on mind that your browser use some keys 
         //to call some function, so we'll prevent this
         e.preventDefault();

         //now we caught the key code, yabadabadoo!!
         var keyCode = e.keyCode || e.which;

         //your keyCode contains the key code, F1 to F12 
         //is among 112 and 123. Just it.
         console.log(keyCode);       
    });
});

You can do this with jquery like this:

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });

Wow it is very simple. i'm blame to write this, why no one make it before?

$(function(){
    //Yes! use keydown 'cus some keys is fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well you need keep on mind that your browser use some keys 
         //to call some function, so we'll prevent this
         e.preventDefault();

         //now we caught the key code, yabadabadoo!!
         var keyCode = e.keyCode || e.which;

         //your keyCode contains the key code, F1 to F12 
         //is among 112 and 123. Just it.
         console.log(keyCode);       
    });
});

I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.


Without other external class you can create your personal hack code simply using

event.keyCode

Another help for all, I think is this test page for intercept the keyCode (simply copy and past in new file.html for testing your event).

 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 <style type="text/css">
 td,th{border:2px solid #aaa;}
 </style>
 <script type="text/javascript">
 var t_cel,tc_ln;
 if(document.addEventListener){ //code for Moz
   document.addEventListener("keydown",keyCapt,false); 
   document.addEventListener("keyup",keyCapt,false);
   document.addEventListener("keypress",keyCapt,false);
 }else{
   document.attachEvent("onkeydown",keyCapt); //code for IE
   document.attachEvent("onkeyup",keyCapt); 
   document.attachEvent("onkeypress",keyCapt); 
 }
 function keyCapt(e){
   if(typeof window.event!="undefined"){
    e=window.event;//code for IE
   }
   if(e.type=="keydown"){
    t_cel[0].innerHTML=e.keyCode;
    t_cel[3].innerHTML=e.charCode;
   }else if(e.type=="keyup"){
    t_cel[1].innerHTML=e.keyCode;
    t_cel[4].innerHTML=e.charCode;
   }else if(e.type=="keypress"){
    t_cel[2].innerHTML=e.keyCode;
    t_cel[5].innerHTML=e.charCode;
   }
 }
 window.onload=function(){
   t_cel=document.getElementById("tblOne").getElementsByTagName("td");
   tc_ln=t_cel.length;
 }
 </script>
 </head>
 <body>
 <table id="tblOne">
 <tr>
 <th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
 </tr>
 <tr>
 <th>keyCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 <tr>
 <th>charCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 </table>
 <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
 </body>
 </html>

Here is a working demo so you can try it right here:

_x000D_
_x000D_
var t_cel, tc_ln;_x000D_
if (document.addEventListener) { //code for Moz_x000D_
  document.addEventListener("keydown", keyCapt, false);_x000D_
  document.addEventListener("keyup", keyCapt, false);_x000D_
  document.addEventListener("keypress", keyCapt, false);_x000D_
} else {_x000D_
  document.attachEvent("onkeydown", keyCapt); //code for IE_x000D_
  document.attachEvent("onkeyup", keyCapt);_x000D_
  document.attachEvent("onkeypress", keyCapt);_x000D_
}_x000D_
_x000D_
function keyCapt(e) {_x000D_
  if (typeof window.event != "undefined") {_x000D_
    e = window.event; //code for IE_x000D_
  }_x000D_
  if (e.type == "keydown") {_x000D_
    t_cel[0].innerHTML = e.keyCode;_x000D_
    t_cel[3].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keyup") {_x000D_
    t_cel[1].innerHTML = e.keyCode;_x000D_
    t_cel[4].innerHTML = e.charCode;_x000D_
  } else if (e.type == "keypress") {_x000D_
    t_cel[2].innerHTML = e.keyCode;_x000D_
    t_cel[5].innerHTML = e.charCode;_x000D_
  }_x000D_
}_x000D_
window.onload = function() {_x000D_
  t_cel = document.getElementById("tblOne").getElementsByTagName("td");_x000D_
  tc_ln = t_cel.length;_x000D_
}
_x000D_
td,_x000D_
th {_x000D_
  border: 2px solid #aaa;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Untitled</title>_x000D_
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table id="tblOne">_x000D_
    <tr>_x000D_
      <th style="border:none;"></th>_x000D_
      <th>onkeydown</th>_x000D_
      <th>onkeyup</th>_x000D_
      <th>onkeypress</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>keyCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>charCode</th>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


Try this solution if works.

window.onkeypress = function(e) {
    if ((e.which || e.keyCode) == 116) {
        alert("fresh");
    }
}

Solution in ES6 for modern browsers and IE11 (with transpilation to ES5):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

My solution to this problem is:

document.onkeypress = function (event) {
    event = (event || window.event);
    if (event.keyCode == 123) { 
         return false;
    }
}

With the magic number 123 which is the key F12.


One of the problems in trapping the F1-F12 keys is that the default function must also be overridden. Here is an example of an implementation of the F1 'Help' key, with the override that prevents the default help pop-up. This solution can be extended for the F2-F12 keys. Also, this example purposely does not capture combination keys, but this can be altered as well.

<html>
<head>
<!-- Note:  reference your JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <h1>F-key trap example</h1>
    <div><h2>Example:  Press the 'F1' key to open help</h2></div>
    <script type="text/javascript">
        //uncomment to prevent on startup
        //removeDefaultFunction();          
        /** Prevents the default function such as the help pop-up **/
        function removeDefaultFunction()
        {
            window.onhelp = function () { return false; }
        }
        /** use keydown event and trap only the F-key, 
            but not combinations with SHIFT/CTRL/ALT **/
        $(window).bind('keydown', function(e) {
            //This is the F1 key code, but NOT with SHIFT/CTRL/ALT
            var keyCode = e.keyCode || e.which;
            if((keyCode == 112 || e.key == 'F1') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Open help window here instead of alert
                alert('F1 Help key opened, ' + keyCode);
                }
            // Add other F-keys here:
            else if((keyCode == 113 || e.key == 'F2') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Do something else for F2
                alert('F2 key opened, ' + keyCode);
                }
        });
    </script>
</body>
</html>

I borrowed a similar solution from a related SO article in developing this. Let me know if this worked for you as well.


Add a shortcut:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

Start reacting to shortcuts:

$.Shortcuts.start();

Add a shortcut to “another” list:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

Activate “another” list:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

Stop (unbind event handlers):

$.Shortcuts.stop();


Tutorial:
http://www.stepanreznikov.com/js-shortcuts/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to keyboard

How do I check if a Key is pressed on C++ Move a view up only when the keyboard covers an input field Move textfield when keyboard appears swift Xcode iOS 8 Keyboard types not supported Xcode 6: Keyboard does not show up in simulator How to dismiss keyboard iOS programmatically when pressing return Detect key input in Python Getting Keyboard Input Press Keyboard keys using a batch file Keylistener in Javascript

Examples related to keyboard-events

How to generate keyboard events? Android Use Done button on Keyboard to click button Detecting arrow key presses in JavaScript How can I programmatically generate keypress events in C#? How to detect pressing Enter on keyboard using jQuery? Firing a Keyboard Event in Safari, using JavaScript Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser