Most of the code I've seen online uses document.onkeydown
, but MDN only lists window.onkeydown
. This comment also recommends using window.onkeydown
. Is there a difference or a reason to use one over the other?
See the following graphic from Event dispatch and DOM event flow:
There are three event phases:
The capture phase: the event object must propagate through the target's ancestors from the defaultView to the target's parent. This phase is also known as the capturing phase. Event listeners registered for this phase must handle the event before it reaches its target.
The target phase: the event object must arrive at the event object's event target. This phase is also known as the at-target phase. Event listeners registered for this phase must handle the event once it has reached its target. If the event type indicates that the event must not bubble, the event object must halt after completion of this phase.
The bubble phase: the event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the defaultView. This phase is also known as the bubbling phase. Event listeners registered for this phase must handle the event after it has reached its target.
Therefore, the main difference is that event listeners added to window
will handle the event after event listeners added to document
in case of bubble phase; and before in case of capture phase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With