Focus event with dispatchEvent

13,182

The element you fire an event on does not have to be listening for that event, since potentially, the parent element may also be listening for that event.

Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a focus event does not cause the element to receive focus (you must use its focus() method for that), manually firing a submit event does not submit a form (use the submit() method), manually firing a key event does not cause that letter to appear in a focused text input, and manually firing a click event on a link does not cause the link to be activated, etc. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

Also note that you should use fireEvent(), if you are working on IE. Also, the main difference between the dispatchEvent and fireEvent methods is that the dispatchEvent method invokes the default action of the event, the fireEvent method does not.

so for the solution please try this

test.onfocus = function(event) {
  console.log('focused');
  if( ! test.hasFocus() ) {
    test.focus();
  }
}
Share:
13,182
Viktor
Author by

Viktor

Updated on June 19, 2022

Comments

  • Viktor
    Viktor almost 2 years

    When I trigger a focus event with dispatchEvent on an input box, its onfocus is called, but on the UI the input box is not focused. Is there any reason for this behavior?

    var test = document.getElementById("test");
    test.onfocus = function(event) {
      console.log('focused');
    }
    var e = document.createEvent('Event');
    e.initEvent("focus", true, true);
    test.dispatchEvent(e);
    

    On the other hand this works as expected.

    var test = document.getElementById("test");
    test.focus();
    

    The reason i'm investigating this is that I use ZeptoJS to trigger events and it uses dispatchEvent.

    • Ibu
      Ibu almost 13 years
      on which browser have you tested this? dispatchEvent is not supported in IE8 and under
  • Viktor
    Viktor almost 13 years
    thanks! so you mean that executing test.focus() does not call any event but only calls the test element's focus method?
  • Talha Ahmed Khan
    Talha Ahmed Khan almost 13 years
    No, What i mean that if the test.onfocus() is called it is not necessary that the test will be focused. You have to explicitly call the test.focus() method that will take the cursor to the test element.