Is there a difference between window.onkeydown and document.onkeydown?

Most of the code I've seen on the internet uses document.onkeydown

but MDN lists window.onkeydown

. This comment also recommends using window.onkeydown

. Is there a difference or reason to use one over the other?

+3


source to share


1 answer


See the following figure from Event Dispatch and DOM Event Flow :

graphical representation of an event dispatched in a DOM tree using the DOM event flow

There are three phases of events :



  • Phase : event object should propagate through target ancestors from defaultView to target parent. This phase is also known as the capture phase. Event listeners registered for this phase must handle the event before it reaches the target.

  • Target phase : event object must arrive at event object event target . This phase is also known as the target phase. Event listeners registered for this phase should handle the event as soon as it reaches its target. If the event type indicates that the event should not bubble, the event object should be stopped after the completion of this phase.

  • Bubble phase : the event object propagates through the target ancestors in reverse order, starting at the target parent and ending with the defaultView . This phase is also known as the bubble phase. Event listeners registered for this phase must handle the event after the goal has been reached.

Therefore, the main difference is that event listeners added to window

will handle the event after adding event listeners document

in the case of a bubble phase; and before that in the case of the capture phase.

+5


source







All Articles