How to detect Key Press combinations like ALT+1 in jquery
Try “keypress” evenHandler in jQuery:
Notice Below Code, Although this code is correct but will not work. The reason behind is when we press CTRL or ALT key on a web page, it executes browser’s shortcut first. For example ( CTRL + 1 ) will switch to first tab.
jQuery(document).bind('keypress', function(e) {
if( e.which === 49 and e.altKey ) {
console.log('ALT + 1 is pressed');
}
});
So we need a better logic which can work better in all cases, keep in mind:
When we press combination of keys we keep first key pressed ( CTRL , ALT, SHIFT ) and then press and release second key.
var keyDownCode = -999; // default anything which is not a keycode
var keyUpCode = -999; // default anything which is not a keycode
$(document).keydown(function (e) {
keyDownCode = e.which;
$("#log").append("You Down = "+keyDownCode+"<br>");
});
$(document).keyup(function (e) {
keyUpCode = e.which;
$("#log").append("You Up = "+keyUpCode+"<br>");
// check the condition now;
if(keyDownCode == 18 && keyUpCode == 49){
$("#log").append("You Pressed ALT + 1 <br>");
}
});
Leave a Reply