Sunday, March 21, 2021

Javascript Listening for a specific Key press

 If you want to know what key was press in a web page, you will normally do a document.addEventListener('keydown',myFunc) function. However, if you only want to act upon s specific key then the situation is slightly different becauses addEventListener does not have function to return anything.

Fortunately, there is a "bind" function in the event listener. by defining the event listener as

document.addEventListener('keydown',myFunc.bind(event))

In myFunc then you could use event.keyCode to determine which key was pressed and bypass any other.

There is an issue here. You can't capture key combinations. Keys like Alt-s will be passed as two event instead of one thus the function is triggered twice. But for just a simple key press like pressing the space-bar, the script works quite well.