-3

The below code works in Chrome but not Firefox. How do I get the focus event to fire?

http://jsfiddle.net/aeko9o7t/1/

HTML:

<input id="one" type="text" />
<input id="two" type="text" />

JavaScript:

var one = document.getElementById( "one" );
var two = document.getElementById( "two" );

one.addEventListener( "focus", function() { console.log( "one called" ); }, false );
one.focus();
two.addEventListener( "focus", function() { console.log( "two called" ); }, false );
two.focus();

In firefox neither one is focused and the console never writes anything, but in Chrome it works.

Even adding in setTimeout still doesn't cause it to fire: http://jsfiddle.net/aeko9o7t/4/

raam86
  • 6,785
  • 2
  • 31
  • 46
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • 1
    Working in FF 31. See http://jsfiddle.net/aeko9o7t/4/show/ (or right click in result pane and this frame -> reload) – Salman A Sep 11 '14 at 20:28

1 Answers1

1

In general, you can only rely on events being triggered due to user interactions or asynchronous events. Browsers differ on whether they fire events for actions that are caused by program code.

So FF will run the event listeners when you click on the fields to give them focus, but not when the focus is given from the .focus() method.

There's some discussion of these types of events in these questions:

Is JavaScript guaranteed to be single-threaded?

Is there something as "immediate events" in Javascript?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • While your first point might be correct, it has nothing to do with the two links you posted but is **much** more likely due to Mozilla's security concerns. However, it seems not to be following the spec. – Don Rhummy Sep 11 '14 at 20:09