Reputation: 1668
Hi i like to prevent the default behaviour of ctrl+s(save) so i tried the below code
jQuery(document).bind("keydown", function(e) {
if(e.ctrlKey && (e.which == 83)) {
e.preventDefault();
alert("Ctrl+S");
return false;
}
});
But this is preventing only in chrome not in firefox.In firefox the save dialog is poping up why is this happening or am i missing something.Any help?
Upvotes: 3
Views: 1347
Reputation: 171
Try this....
$(document).bind("keydown", function(e) {
if(e.ctrlKey && (e.which == 83)) {
e.preventDefault();
setTimeout(function() {
alert("Ctrl+S");
}, 1000);
return false;
}
});
Using an alert will complete the thread execution, only for the thread to be picked up again once the OK button of the alert is clicked. I can only imagine that at this point the 'preventDefault' just hasn't been acknowledged by Firefox (even though you're calling this before the alert) and it continues to display the Save As dialog.
I've used a setTimeout to delay the alert by 1 second, although I'm sure using 0 will have the same effect... simply pushing the function (now async) showing the alert to the back of the execution stack, which will allow the browser to complete the execution of the preventDefault.
I know you don't want the 'alert', but thought I'd provide an explanation of the behaviour.
Upvotes: 3
Reputation: 3778
Try below code:
$(document).ready(function(){
$(document).bind('keydown', function(event) {
//19 for Mac Command+S
if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
event.preventDefault();
console.log("Ctrl-s pressed");
return false;
});
});
JS Fiddle: http://jsfiddle.net/dpHk9/
Explanation
The below code converts unicode number into corresponding character:
String.fromCharCode(number) //returns A for 65
The below code represents control key:
event.ctrlKey
On a MAC, command+s
returns 19
Upvotes: 0