Focus event with dispatcher

When I fire an event focuswith dispatchEventin the input field, it is called onfocus, but in the user interface the input field is not focused. Is there a 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, it works as expected.

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

The reason I am investigating this is because I use ZeptoJS to fire events and use dispatchEvent.

+5
source share
1 answer

The element that you are triggering the event should not listen to this event, since the potentially parent element can also listen to this event.

, , . , focus , ( focus()), submit ( submit()), , , .. , , .

, fireEvent(), IE. , dispatchEvent fireEvent , dispatchEvent , fireEvent .

test.onfocus = function(event) {
  console.log('focused');
  if( ! test.hasFocus() ) {
    test.focus();
  }
}
+2

All Articles