Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 720
Yay295 Avatar asked Nov 22 '14 01:11

Yay295


1 Answers

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.

like image 161
Oriol Avatar answered Sep 30 '22 01:09

Oriol