Skip to content
Advertisement

In JavaScript, manually controlling order of event listeners

Assuming that FORM contains INPUT, have the following listeners:

JavaScript

JavaScript

Desired order of firing

JavaScript

Nature of problem and attempted solutions

Own code at FORM level, formFirst, formLast and middle, but have no access to INPUT code, inputFirst and inputLast – although could add own listeners on the INPUT.

Attempt 1 modify formFirst() to create and dispatch a new change Event (would be ignored within formFirst) that would call inputFirst(), but have no way of stopping propagation to prevent inputLast() being called subsequently.

Attempt 2 add middle added as listener to INPUT, but cannot guarantee firing order of two listeners of same type and same useCapture.


Premise of Attempt 2 is incorrect – firing order is determined by declaration order within the target Element.

Here are the rules

  1. non-target Element triggers with useCapture=false, starting at the outermost Element and working toward the target Element

    a) if more than one useCapture=true triggers for same element, then order of declaration.

  2. at target Element, order of declaration, regardless of useCapture

  3. non-target Element triggers with useCapture=false, starting at the innermost Element and working away from the target Element

    a) if more than one useCapture=false triggers for same Element, then order of declaration.

Advertisement

Answer

I think that this answers just your question. feel free to commentcontact me for more info.

—– edit ——

OK, I just played with it a little as promised, and I found a very simple solution:

JavaScript

notice:

  • I put the addEventListener part into an init function, so I can call it after the page is loaded and the element are already exist.
  • I have run this just on chrome. So I don’t want to guarantee you things about other browsers.
  • An alternative is writing the event handling on your own. here is an example for that. relaying on this article.

    JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement