I have a button in HTML and I want to provide a shortcut key to it, which should run the functionality as when button clicks what happens.
Is it possible to do something like this using JavaScript or jQuery.
You can do this using plain HTML: accesskey="x". Then you can use alt+x (depending on the browser though if it's alt or something else)
Untested:
$("body").keypress(function(event) {
if ( event.which == 13 ) { // put your own key code here
event.preventDefault();
$("#yourbutton").click();
}
});
It's pretty easy using jQuery. To trigger a button:
$('#my-button').trigger('click');
To monitor for keypress:
$(window).keypress(function (event) {
if (event.which === 13) { // key codes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
event.preventDefault();
$('#my-button').trigger('click');
}
});
Now, if you want to use the Ctrl key or similar you use
if (event.which === 13 && event.ctrlKey)
and similar with event.altKey, event.shiftKey.
$(document).on('keypress', function (e) {
if (e.keyCode === youreKeyCodeHere) {
// if (e.keyCode === youreKeyCodeHere && e.shiftKey === ture) { // shift + keyCode
// if (e.keyCode === youreKeyCodeHere && e.altKey === ture) { // alt + keyCode
// if (e.keyCode === youreKeyCodeHere && e.ctrlKey === ture) { // ctrl + keyCode
$('youreElement').trigger('click');
}
});
Where youreKeyCode can be any of the following javascript char codes , if you're shortcut needs an alt (shift, ctrl ...) use the commented if's . youreElement is the element that holds the click event you whant to fire up.
Related
Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode
How do I recreate ctrl + f shortcut key in my website using react?
I want to use any shortcut to trigger a filter function?
This code may help you.
window.addEventListener("keydown",function (e) {
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
e.preventDefault();
// trigger your filters here
}
})
You can use vanilla javascript document keyup event, e.g.:
document.onkeyup = function(e) {
if (e.ctrlKey && e.which === 70){ // CTRL+F
// Put your code here
}
}
Otherwise, if you want to use something more "react" friendly take a look into https://github.com/jaywcjlove/react-hotkeys#readme
I want to call functions if a particular key is press together with CTRL (windows system)
to test for a particular keyCode I used event.keyCode In this case I got to know the codes for each key. I assumed 17 + 73 will be CTRL + I
This doesn't seem to work except if I check of p only.
I want to be able to check for CTRL + a particular KEY.
Thank you.
What I tried:
//keyboard shorcut to call functions
$(document).on('keydown', function (e) {
if(e.keyCode === 90){ // I want CTL + I
e.preventDefault();
//call image upload func...
triggerUpload(event,$(".camicon"));
return false;
}else if(e.keyCode === 97){ //I want CTL + P
e.preventDefault();
$('.status-btn').click();
return false;
}
});
if(e.keyCode === 90 && e.ctrlKey) {
// CTRL+I
}
else if(e.keyCode === 97 && e.ctrlKey){
// CTRL + P
}
This should work, check if e.ctrlKey is pressed.
I would like a system administrator to easily create new accounts in an application. I was thinking keys alt and shift would trigger the "Create New User" button or defaultButton2 in my application. I can get one key to work, but combining both keys doesn't seem to work.
$(document).ready(function () {
$("input").bind("keydown", function (event) {
var keycode = (event.keyCode ? event.keyCode :
(event.which ? event.which : event.charCode));
if (keycode == 16 && keycode == 18) {
document.getElementById('defaultButton2').click();
return false;
} else {
return true;
}
});
});
The keydown event (mdn) has booleans for the shiftkey, altkey and control key to detect when combinations of buttons are pressed. You can therefore just check those. The keyCode is only for the last key pressed.
If you want to detect other keys, e.g. if "a" and "s" are pressed at the same time, you need to mess around with custom keydown and keyup events and track things yourself.
$('body').on( 'keydown', function(e) {
if( e.altKey && e.shiftKey ) {
console.log( "Both pressed!" );
}
} );
body {
background-color: #DDDDDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click Here
You almost did it right...
$(document).ready(function(){
$("input").keydown(function(e) {
// 18 is the key for alt
if(e.keyCode == 18 && e.shiftKey) {
$("button").click();
}
});
});
Here is a working JSFiddle and if you're looking for the JS keycodes have a look here.
For whatever reason I can't capture "SHIFT+TAB" combination.
I am using the latest jQuery.
Same result if I use other ajax/javascript, etc.
Here is a simple example that should work as I currently understand it...
event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...
function ShiftTab()
{
debugger;
if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
// if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
{
return true;
}
else
{
return false;
}
}
this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.
If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:
$(document).keyup(function (e) {
if (e.which === 9 && e.shiftKey) {
ShiftTab();
}
});
If you're into terse JavaScript:
$(document).keyup(function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
jQuery 1.7+ on syntax:
$(document).on('keyup', function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press
function ShiftTab(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode; // for trans-browser compatibility
if (charCode === 9) {
if (e.shiftKey) {
$('#controlName').focus();
return false;
} else {
return true;
}
}
I took this approach to deal with two specific problems:
onkeypress would not capture tab key press
When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
use same code inside keypress event.
the tab changes the element between keypress and keyup.
here we get event.key = tab and event.shiftKey = true.