1

I try to implement hotkey functionality using jQuery. The goal is to call functions when Ctrl + 'some letter' is pressed. This works when using keypress(), but keypress() doesn't work in Chrome and IE. keydown() works in major browsers, but in this case the problem is - prevention of default browser behavior, i.e. New Window is opened when Ctrl + N is used. My code is:

  var ctrlDown = false;
    jQuery(document).keydown(function (e) {
        e.preventDefault();
        if (e.ctrlKey) {
            ctrlDown = true;
            if (ctrlDown && e.which == 13) {
                alert('ctrl + enter');
            }
            else if (ctrlDown && e.which == 78) {
                alert('Ctrl + N');
            }
        } else {
            ctrlDown = false;
        }
    });

I also tried stopPropagation(), but it didn't help. What can be done in order to prevent browser's default behavior?

SysGen
  • 604
  • 7
  • 29
  • Possible duplicate of http://stackoverflow.com/questions/4604057/jquery-keypress-ctrlc-or-some-combo-like-that – ernd enson May 27 '13 at 17:02
  • try `return false` to stop "browser's default behavior". **Warning!** This is not advised and is going to get very tricky. You're better off using a different "alt" key of some sort, like `shift` or key combo's like `up+b` – SpYk3HH May 27 '13 at 17:13
  • No, that is not a duplication of the question. The code in the link that ernd enson provided works fine if there is only one hotkey. But if there are several hotkeys: when one hotkey will be triggered, the other hotkeys will also be triggered. For example, if we have shortcuts for Ctrl+N, Ctrl+S. Ctrl+N will be pressed, the code for Ctrl+S will be triggered too. –  May 27 '13 at 21:57

0 Answers0