Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With the following html structure:

<div>
<form><span><input></span></form>
</div>
<p>

and the following jquery code:

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

Why doesn't the focus event ever reach my event handler? Binding the event with a selector parameter works fine:

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

Event the next snippet works so the focus event does in fact bubble...

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

Both forms work with click and change events:

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

The only note I found about the focus event's bubbling is relative to older jQuery versions which I don't use. See it in action here

edit 1

Well this is confusing... According to jQuery's focus doc:

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().

And according to jQuery's focusin doc:

The focusin event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).

Is it too late for me or does one contradict the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
392 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...