1

For some reason the following code only fires when the window gets focus, but not when input fields get focus, or any other element (regardless of whether they have a tabindex or not).

I don't want to use someElement.addEventListener method, because the element isn't attached to the view at the time the event listener is added.

var handleFocus = function(event) {
   var el = event.target;
   console.log(el);
}

addEventListener('focus', handleFocus, false);

I basically need to listen for when any input fields are focused on. My reason for wanting to apply it to the parent window, is that the form fields are added and removed from the view at different times (Aurelia).

When the event fires, I want to be able to read properties of the target, to see what actions I need to take.

Any help on this would be super...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
3Dom
  • 795
  • 3
  • 10
  • 22
  • You are not declaring which element is to have the addEventListener added to it. The default is the window i.e. myElement.addEventListener(....). What are you trying to achieve? If it is just highlighting the element then this can be done in CSS. –  Nov 01 '16 at 01:36
  • The `focus` event doesn't bubble, but MDN says you can get event delegation to work by setting the "useCapture" parameter of addEventListener to true. Or use the `focusin` event instead, because it *does* bubble, but MDN says that it isn't supported in FF. – nnnnnn Nov 01 '16 at 01:36
  • @nnnnnn are you saying focus shouldn't fire when you focus on an input? (when you're listening on the window object) – 3Dom Nov 01 '16 at 01:42
  • Yes, if you're listening on a parent element then it won't get a focus event when the child is focused. (But as I also said, MDN says you can work around this by setting the `useCapture` to true instead of false, however I've never tried that: never needed to in my own work.) – nnnnnn Nov 01 '16 at 01:43
  • Yikes, useCapture is very poorly explained by MDN. It works though. Thanks for that. If you write it in an answer I'll tick it off as the accepted solution. – 3Dom Nov 01 '16 at 02:11
  • @nnnnnn not sure if I needed to mention you in the above comment for you to see it... – 3Dom Nov 01 '16 at 02:29
  • "Use capture" seems too vague as an answer, and I am too lazy to figure out the appropriate code (which is why I just posted a comment originally). You could always post the code you ended up using as an answer yourself and then accept that. – nnnnnn Nov 01 '16 at 02:34

1 Answers1

3

Turns out you need to set the 'useCapture' option to true. If you want to know more about 'useCapture' option, this StackOverflow question does a better job than MDN.

Just means I had to change from this:

addEventListener('focus', handleFocus, false);

...to this:

addEventListener('focus', handleFocus, true);
Community
  • 1
  • 1
3Dom
  • 795
  • 3
  • 10
  • 22