Focus and blur jQuery events not bubbling

人走茶凉 提交于 2019-11-28 11:04:51

Yes, it appears the jQuery docs are misleading. I believe the documentation on focus neglected to mention that this was for the elements that aren't involved in user input (@Ohgodwhy listed them above in your question's comments).

I imagine it has something to do with the browser's need to trap the cursor in the input element that has focus, so that it can accept input from the keyboard. In other words, if jQuery allowed it to bubble, then you would never be given the chance to type in the input field.

Either way you'll never get a form to accept a focus event unless you first put a tabindex on it: http://jsfiddle.net/qxLqP/ but if an input based field gets focus first, it will never bubble. By default, the form element doesn't have a tabindex, and you can't set focus to something that doesn't have a tabindex.

I'd just accept @Ohgodwhy's solution of using focusin and then go let the jQuery team know about their confusing documentation.

As Ohgodwhy pointed out, using focusin instead of focus does work.

However, I can't understand how the following code can work if the "focus" event does not bubble:

$('form').on("focus", "span", function(event) {
    $("p").append("focus delegation<br>");
})

If a span child of the form receives the "focus" event, it means that the event bubbled from the input to the span. Even this works!

$('div').on("focus", "form", function(event) {
    $("p").append("focus delegation<br>");
})

So... using "focusin" does fix the problem, but I'm not fully satisfied by this workaround. If anybody has a better answer, I'll happily accept it.

Jquery has a cross browser function which takes care of focus delegations.

Chrome,safari and opera support an event called "DOMFocusIn" which actually delegates.

IE supports an event "focusin" for delegating focus.

Firefox supports "focus" only on capturing phase and not bubbling phase.

jQuery made a cross browser event which is "focus" which actually delegates.

I hope this answers all your doubts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!