2

I came across this code:

window.addEventListener('keydown',function(e){
keyState[e.keyCode] = true;
},true);

And I don't get what the ",true);" part does. Could somebody please explain its purpose? Thanks in advance!

Anna Leo
  • 37
  • 3
  • 5
    MDN explains it: [MDN addEventListener see useCapture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – epascarello Nov 16 '16 at 17:07

2 Answers2

4

From MDN's notes on addEventListener, that is the useCapture flag:

useCapture Optional

A Boolean that indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

You can catch event in bubbling phase or in capturing phase.

window.addEventListener('keydown',function(e){
    keyState[e.keyCode] = true;
},true);

In your code snippet true is useCapture flag, meaning that we specify capturing phase.

The next question probably would be What is event bubbling and capturing?

Community
  • 1
  • 1
oKonyk
  • 1,468
  • 11
  • 16