Reputation: 89
$(window).keypress(function(event) {
if (event.which == 115 && event.ctrlKey){
myfunction();
}
});
myfunction(){
alert("Key pressed Ctrl+s");
}
When Ctrl+S was pressed, I don't see this myfunction is trigger. Can anyone help.? I am new to jQuery. Thanks in advance.
Upvotes: 4
Views: 5947
Reputation:
As Prabhas said, your function definition was wrong.
But you'll also need to use keydown
, not keypress
.
Plain Javascript (which could be unreliable b/c some browsers use event.charCode
and others event.keyCode
):
window.addEventListener('keydown', function(e) {
if (e.keyCode == 83 && event.ctrlKey) {
myfunction();
}
});
jQuery (which normalises event.which
for charCode
and keyCode
, see: http://api.jquery.com/event.which/):
$(document).bind("keydown", function(e) {
if(e.which == 83 && event.ctrlKey){
myfunction();
}
});
Upvotes: 1
Reputation: 11269
Listen for keyup
and keydown
. Also, the key code for 's' is 83. This reliably works:
$(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.which == 83){
myfunction();
}
});
function myfunction(){
alert("Key pressed Ctrl+s");
}
Upvotes: 5
Reputation: 282
Function definition is wrong:
This should work
$(window).keypress(function(event) {
if (event.which == 115 && event.ctrlKey){
myfunction();
return false;
}
});
function myfunction(){
alert("Key pressed Ctrl+s");
}
Upvotes: 3