Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  135] [ 3]  / answers: 1 / hits: 15170  / 13 Years ago, tue, july 5, 2011, 12:00:00

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.


More From » events

 Answers
4

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

[#91355] Saturday, July 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;