Reputation: 63
I am confused as to why when I press a key, my function is not logging the keydown event?
window.addEventListener('keydown', function(e) {
console.log(e);
});
<h1> Start typing </h1>
Upvotes: 1
Views: 3322
Reputation: 9676
Your snippet seems to be okay. So it might have to do with the surrounding environment, where you run it.
(That is, if the other answers using document
did not already help you.)
Please investigate the situation where it fails. A possible reason could be that the keyEvent
is cancelled by any EventListener along the bubble way.
You are fetching the keydown
at the top-most level, the window level (even higher than the document level).
If the bubbling is stopped along the event way, you won't see it.
Try for example
document.addEventListener("keydown", function(e) {
e.stopPropagation();
});
This will also prevent you from seeing the keydown in your orignal event listener.
Upvotes: 1
Reputation: 420
I believe that the right approach has to be use the document object and not the window object.
A code like the following should work:
document.addEventListener('keydown', function(e) {
console.log("event", e);
});
Upvotes: 2