0

I used the instructions here to turn ` into a shortcut thusly:

function reset_shortcut_key(e) {
    if (e.keyCode == 192) reset_data();
}

document.addEventListener('keyup', reset_shortcut_key, false);

It loads the next problem successfully, but when I hit this hotkey while focused on a <form> <input> </form> environment, the ` character momentarily shows up (before the next problem is loaded).

A fill-in-the-gaps puzzle with a ` character showing.

I want to prevent it from showing the ` character.

Question: How do I prevent the hotkey ` from being added to a form input?

Other related questions are How can I prevent \ from being added from the form input? (but this is about stripping slashes) and Javascript -> Hotkeys -> Disable for input fields (and here) (but I want the hotkey to work).


Edit: Judging from the current comment and answer, the appropriate function is event.preventDefault(). I'm still not clear on how to actually implement this.

Simply adding it before or after document.addEventListener('keyup', reset_shortcut_key, false); doesn't do anything. Beyond this,

        document.addEventListener("keyup", function(event) {
           event.preventDefault();
           reset_shortcut_key();
       }, false);

and

        document.querySelector("#input-guess").addEventListener("keyup", function(event) {
           event.preventDefault();
           reset_shortcut_key();
       }, false);

(where id="input-guess" is the name of my <input>) both prevent reset_shortcut_key() from being called. Modifying reset_shortcut_key as follows doesn't change anything:

        function reset_shortcut_key(e) {
            e.preventDefault();
            if(e.keyCode == 192) reset_data();
        }

At this point, I'm just making guesses on what to do.

2 Answers2

1

Have you tried this? https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

event.preventDefault();
Sam Andreatta
  • 183
  • 3
  • 13
0

It turns out that there was a second issue: I needed to use keydown (instead of keyup). After making that change, the following code (utilizing preventDefault()) works:

function reset_shortcut_key(e) {
  if(e.keyCode == 192) {
    e.preventDefault();
    reset_data();
  }
}