Reputation: 6188
Can a web page detect keyboard input without text input fields or with text input fields unfocused?
Upvotes: 2
Views: 74
Reputation: 464
You can add onkeydown
handler on document
, you just need to have the focus on the window.
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
console.log('left');
break;
case 38:
console.log('up');
break;
case 39:
console.log('right');
break;
case 40:
console.log('down');
break;
}
};
Upvotes: 0
Reputation: 2542
add an event listener to the document (run the example, and click on it to activate it, otherwise its document won't have the focus, this is intended to work on a standalone page rather than embedded frame)
document.addEventListener('keydown', keydownCallback, false);
function keydownCallback(e) {
console.log(e.keyCode + ': "' + String.fromCharCode(e.keyCode) + '"');
}
Upvotes: 3