0

I would like to add an event handler to a keydown event that I want to be processed in advance of other handlers. Right now it seems to be on the top just after my addEventListener call, but after some interaction with the user, another javascript library's listener always ends up ahead of it.

If I want pressing key X to execute my listener and no other, is there any way to carry that out in javascript, short of modifying all external js on the page that might add a handler?

Hasse1987
  • 243
  • 1
  • 9
  • Possible duplicate of [jQuery event handlers always execute in order they were bound - any way around this?](http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t) - if you're looking for a pure dom solution check [this](http://stackoverflow.com/questions/2930424/add-event-to-top-of-event-stack-using-jquery) – h2ooooooo Dec 07 '16 at 18:22

1 Answers1

1

DOM2 (addEventListener) handlers are called in the order in which they were registered. So as long as you register yours first, it will be called first, and you can prevent others from being called by using stopPropagation and stopImmediatePropagation.

The above is in relation to the specific element, however. If your handler is on a container element and there's an element inside that container with a handler directly attached to it, then all of the handlers for that inner element are called before yours on the container element (this is for bubbling; there's another phase called capture where it's the other way around, but almost no one uses it). [See the old DOM3 events spec (but it's still valid).]

So for what you're describing, it sounds like you have your handler on a container element, and the library has its handler on an element inside that container. To get in front of that handler, you'd have to register yours on that specific element first, before that lib does.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I have my keydown handler registered to the document, so I guess if the other library registered to any inside element it would get ahead. A keydown listener on a specific element in the document means what, that it will fire when that element is somehow in focus and a key is pressed? (I'm asking because I'm wondering where to begin looking for that other handler.) – Hasse1987 Dec 07 '16 at 18:38
  • @Hasse1987: Yes, exactly. – T.J. Crowder Dec 07 '16 at 18:40