4

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?

Talon
  • 4,937
  • 10
  • 43
  • 57

2 Answers2

9

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.

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • 2
    Yeah you're right, looks like the prevention needs to be the first thing to fire. – Talon Feb 13 '13 at 19:06
  • 1
    @Talon I believe this is more of Firefox's alert bug. I've run on issues with alerts before as they currently are not 100% synchronous. See this [test case](http://jsbin.com/ecubot/9/edit). – Fabrício Matté Feb 13 '13 at 19:08
  • 2
    Cool one dude. Helped me a lot. Thank you :) – Sherin Jose Jun 16 '15 at 11:48
  • I think firefox is right up there with IE regarding bugs. Hope they fix some of them instead of just ignoring them. They seem to just ignore their bug reports! – www139 Dec 27 '15 at 18:56
1

This worked for me:

<script>
        $(document).bind('keypress', 'Ctrl+s',
            function (event) {
                event.preventDefault();
                alert('saving?');
            });
</script>
amhed
  • 3,649
  • 2
  • 31
  • 56