13

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?

0

1 Answer 1

22

See the following graphic 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 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.

4
  • I'm guessing the reason to use window over document is because it doesn't have to propagate as far?
    – Yay295
    Commented Nov 22, 2014 at 2:11
  • 1
    @Yay295 Did you mean the opposite?
    – MCTaylor17
    Commented Nov 22, 2014 at 2:36
  • As I understand it, if you use window it goes window->event->window, and if you use document it goes window->document->event->document->window.
    – Yay295
    Commented Nov 22, 2014 at 2:44
  • @Yay295 The event flow is always the same, it doesn't depend on your event listeners. But depending on which node you attach your event listener, it will run in a different moment of that event flow.
    – Oriol
    Commented Nov 22, 2014 at 15:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.