Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
Talon Avatar asked Dec 26 '22 09:12

Talon


2 Answers

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.

like image 91
Fabrício Matté Avatar answered Jan 05 '23 18:01

Fabrício Matté


This worked for me:

<script>
        $(document).bind('keypress', 'Ctrl+s',
            function (event) {
                event.preventDefault();
                alert('saving?');
            });
</script>
like image 25
amhed Avatar answered Jan 05 '23 18:01

amhed