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

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?

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");
});

The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html
What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).

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.

It is very simple.
$(function(){
//Yes! use keydown because some keys are fired only in this trigger,
//such arrows keys
$("body").keydown(function(e){
//well so 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.
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);
});
});

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> </td><td> </td><td> </td>
</tr>
<tr>
<th>charCode</th><td> </td><td> </td><td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>
Here is a working demo so you can try it right here:
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;
}
td,
th {
border: 2px solid #aaa;
}
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</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> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th>charCode</th>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>

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;
};

This works for me.
if(code ==112) {
alert("F1 was pressed!!");
return false;
}
F2 - 113,
F3 - 114,
F4 - 115,
and so fort.

You can use Vanilla Javascript and the KeyboardEvents keydown, keypress or keyup.
Use event.key (preferably) or event.code and compare them against the key name like event.key === "F1".
When working with Function keys you probably want to suppress the default behaviour (On windows many of the function keys are used by the browser).
This can be achieved by calling preventDefault() on the keydown event.
Even if you want to listen to the keyup event you need to call preventDefault() on the keydown event, because the browser shortcut is bound to that event.
Keep in mind, that calling preventDefault() on keydown will also suppress the keypress event.
document
.addEventListener("keydown", e => {
if(e.key === "F1") {
// Suppress default behaviour
// e.g. F1 in Microsoft Edge on Windows usually opens Windows help
e.preventDefault()
}
})
document
.addEventListener("keyup", e => {
if(e.key === "F1") {
// Handle the keyup event
doSomething()
}
})

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.

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.

Consider that your app will not be remotely mobile friendly.

Just add this event listener:
function keyDown(e)
{
let charStr, key = e.which || e.keyCode;
if (key >= 112 && key <= 123)
{
e.preventDefault();
e.stopPropagation();
charStr = "F" + (key - 111);
switch (charStr)
{
case "F1":
alert("F1");
break;
case "F2":
alert("F2");
break;
default:
alert("Other F key");
break;
}
}
}
document.addEventListener('keydown', keyDown);
This has very good browser compatibility. I don't know about Internet Explorer 8 or Mozilla FireFox 3, but hardly still relevant in 2022.

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/

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

You can do this with jquery like this:
$("#elemenId").keydown(function (e) {
if(e.key == "F12"){
console.log(e.key);
}
});

Related

How to submit the form when pressing Ctrl + S (instead of "save the webpage") in JavaScript? [duplicate]

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Why doesn't my function override the Alt+D keydown event in Microsoft Edge?

I am unable to override the Alt+D keydown event in Microsoft Edge using JavaScript; it works for all other browsers, though. It's navigating to the address bar.
Here's my on keydown event
$(document).keydown(function (e) {
if (e.altKey && e.key == "d") {
e.cancelBubble = true;
e.returnValue = false;
e.preventDefault();
e.stopPropagation();
alert();
}
});
We had again tested the issue and we found that it is happened due to conflict.
As you know, Alt + D key is a short cut key for selecting the address bar in MS Edge browser.
So it always executes instead of your code.
As we cannot change this shortcut key, if it is possible for you then you can try to use any other letter instead of D in a combination.
For example, here in a test I am using E letter. This can be the work around for this issue.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).keydown(function (e) {
if (e.altKey && e.key == "e") {
e.cancelBubble = true;
e.returnValue = false;
e.preventDefault();
e.stopPropagation();
alert("hello...");
}
});
});
</script>
</head>
<body>
<h2>This is a test. Press Alt + e</h2>
</body>
</html>
Output:

Javascript: Prevent page refresh via Ctrl and R

I am trying to prevent page refresh only when user clicks Ctrl with R.
I try with the preventDefault() method as following but it does not work:
function disableCtrlR(s) { if ((s.which || s.keyCode) == 17 && (s.which || s.keyCode) == 82) s.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableCtrlR);
});
Any help on this will be appreciated. Thanks.
PS. I know this is not an ideal solution but this is the only solution for me to solve the bug on my webpage while waiting for the bug to be resolved.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("keydown", function(e) {
e = e || window.event;
if (e.ctrlKey) {
var c = e.which || e.keyCode;
if (c == 82) {
e.preventDefault();
e.stopPropagation();
}
}
});
});
</script>
<h1>If you click in here, you won't be able to refresh with Ctrl+R</h1>
<input type="text" />
Using jQuery 2.1.1, this will disable reload by Ctrl+R
To check if there is a control key pressed simultaneously in an key event, you'll check for the KeyboardEvent.ctrlKey property.
// beware ES6 below, will fail in Netscape
onkeydown = e => {
if(e.key === 'r' && e.ctrlKey){
e.preventDefault();
console.log('ctrl + r')
}
}
<input autofocus>
Addendum:
As you mentioned in your question, this is very-much "not an ideal solution". Blocking default browser behavior should be made only on special cases, like here blocking the ctrl+R shortcut should only be done on some part of a web-application that really needs this shortcut, and not on the document itself. That's part of why I never talked about blocking the page refresh in this answer (which would need some extra work to work in this intent on all platforms).

can not disable Ctrl+O by JavaScript in IE 11

I'm trying to disable Ctrl+o key combination in IE, the following code works fine in all IE versions except IE 11 unless I do an alert as you see in code below:
document.onkeydown = function(event) {
var x = event.keyCode;
console.log(event.keyCode);
console.log(event.ctrlKey);
if ((x == 79) && (event.ctrlKey)) {
if(navigator.userAgent.match(/rv:11.0/i)){
alert('Disabled');
}
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
event.stopPropagation();
event.preventDefault();
return false;
}
};
I was wondering if anyone else is experiencing the same issue and they have solved it. :-)
Thanks.
Alex
I have no good solution unfortunately, but have created a case with Microsoft, and made a jfiddle that demonstrates the issue.
The only way we have found around this is the use of the:
<meta http-equiv="X-UA-Compatible" content="IE=7">
header, but there's no telling when support for that will go away - not to mention the obvious side-effects of running in IE7 mode.
Some additional notes:
Although the interception works natively on IE8 and IE9, only the IE=7 UA mode works
A page reload is required for the header to take effect, whether it is in the page or returned in the server response i.e. you cannot selectively jump in an out of IE7 mode in a single page app
Here is a link to the standards that IE11 was built against: http://www.w3.org/TR/DOM-Level-3-Events/#KeyboardEvent-supplemental-interface
Fiddle:
http://jsfiddle.net/bw5sLd15/1/
// The kitchen sink
function killKey( event ) {
event.cancelBubble = true;
event.bubbles = false;
event.returnValue = false;
event.stopPropagation();
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
I came to the same conclusion as Alex & Max. In my specific use case, forcing compatibility mode would break other features.
I believe that in most cases a confirm dialog is the best workaround, as it still feels somewhat natural to the user - save for the extra step involved.
http://jsfiddle.net/dperish/sp72c0wt/3/
HTML:
<h1>Demonstration of IE11 event bubbling issue</h1>
<label>Enable Workaround<input type="checkbox" id="enableWorkaround"></label>
<p>Pressing CTRL-P or CTRL-O should NOT show the default open/print dialogs. The only workaround seems to be to interrupt the main thread either with alert(), confirm(), or by hitting a breakpoint in a debugger. </p>
<p>Unfortunately, a synchronous/blocking XHR call was not useful for this purpose. Nor was using the browser-specific showModalDialog.</p>
<div id="output"></div>
Javascript:
function onKeyDown(e) {
e = e || window.event;
if ((e.keyCode === 79 || e.keyCode === 80) && e.ctrlKey) {
e.preventDefault();
e.stopPropagation();
e.returnValue = false;
if ($("#enableWorkaround").is(":checked")) {
if (confirm("Run some custom method?")) {
customMethod(e.keyCode);
}
}
else {
customMethod(e.keyCode);
}
return false;
}
}
function customMethod(x) {
$("#output").append("<p>CustomMethod Says: KeyCode = " + x + "</p>");
return false;
}
$(document).ready(function() {
$(document).on("keydown", function (e) {
onKeyDown(e);
});
});

How do I capture a CTRL-S without jQuery or any other library?

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Categories

Resources