Talon
Talon

Reputation: 4995

Can't override ctrl+s in Firefox using jQuery Hotkeys

I'm using the jQuery Hotkeys plugin: http://code.google.com/p/js-hotkeys/

Here is the code i'm using:

$(document).bind('keydown', 'Ctrl+s', function(event) { alert('saving?'); return false; });

In Chrome it works fine and the Ctrl+s default functionality is over-ridden, but in Firefox it fires the alert and it also tries to save the html page.

I know there has to be someway to get it to work, Wordpress in Firefox let's you press ctrl+s to save.

Any ideas?

Upvotes: 4

Views: 3745

Answers (2)

Fabrício Matté
Fabrício Matté

Reputation: 70159

Seems like a bug in Firefox where alert breaks the synchronicity of your code. Delaying the alert seems to workaround the issue:

$(document).bind('keydown', 'Ctrl+s', function(event) {
  setTimeout(function() {
    alert('saving?');
  }, 0);
  return false;
});

JSbin


Here's a test case to prove my bug claim.

$(document).bind('keydown', 'Ctrl+s', function(event) {
  event.preventDefault();
});

The above (bin) will prevent the save dialog nicely. Now if you add an alert either before or after it, the save dialog will appear nevertheless if you do event.preventDefault() and event.stopImmediatePropagation() or return false:

$(document).bind('keydown', 'Ctrl+s', function(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
  alert('saving?');
  return false;
});

Bin

event.preventDefault() on its own is enough to prevent the save dialog if there are no alerts, now with an alert it is possible to prevent the default action.

Upvotes: 9

amhed
amhed

Reputation: 3659

This worked for me:

<script>
        $(document).bind('keypress', 'Ctrl+s',
            function (event) {
                event.preventDefault();
                alert('saving?');
            });
</script>

Upvotes: 1

Related Questions