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
.
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();
}
}