0

I want keystrokes to trigger some javascript code. I found Capture key press without placing an input element on the page? and it works, except that the browser gets those keystrokes, too, and does a lot of unwanted things, for example, it starts "Quick Find" and takes the focus away.

So how can I tell the browser to ignore a range of keys for a specific window?

Community
  • 1
  • 1
Gyro Gearloose
  • 1,056
  • 1
  • 9
  • 26

1 Answers1

2

Usually by using return false in the keydown event handler would be sufficient to prevent default browser behaviour. Eg:

window.onkeydown = function(event){
    var keyCode = event.keyCode;
    if (keyCode == 13) {    //prevent enter key from being detected
        return false;
    }
}

Reference for key codes: https://css-tricks.com/snippets/javascript/javascript-keycodes/

mylee
  • 1,293
  • 1
  • 9
  • 14
  • It works! And +1 for the link to the key codes. But can you please explain what that return false exactly does? It doesn't stop the event bubbling further up? – Gyro Gearloose Jan 13 '16 at 13:02
  • Hm, it worked the first few tries, but now the Quick Find opens again. Confusing. Will have to experiment for a while. – Gyro Gearloose Jan 13 '16 at 13:06
  • return false will usually be an indicator to browsers to ignore that event, however to be safe you can add event.preventDefault() and event.stopPropagation() if they exist – mylee Jan 13 '16 at 13:16
  • Looks like it works for keydown, but not keyup, but what have I seen the first time? Confusing. – Gyro Gearloose Jan 13 '16 at 13:23
  • It should be possible to do this window.onkeydown = window.onkeyup = function(event)... – mylee Jan 13 '16 at 13:26
  • Ouch, I see what happened. When using onkeyup the onkeydown event has already escaped to the browser! No with "onkeydown="return false;" onkeyup="event.preventDef..." it works. – Gyro Gearloose Jan 13 '16 at 13:42