Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus event with dispatchEvent

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.

like image 285
Viktor Avatar asked Jul 05 '11 04:07

Viktor


People also ask

What is dispatchEvent used for?

The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected EventListener s in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent() .

Which event is fired when an element loses its focus?

The focusout event fires when an element has lost focus, after the blur event. The two events differ in that focusout bubbles, while blur does not. The opposite of focusout is the focusin event, which fires when the element has received focus.


1 Answers

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();
  }
}
like image 133
Talha Ahmed Khan Avatar answered Sep 23 '22 00:09

Talha Ahmed Khan