Skip to main content

Bug Tracker

Side navigation

#12185 closed bug (worksforme)

Opened August 02, 2012 07:24PM UTC

Closed August 15, 2012 01:17PM UTC

Delegate focus/blur event fires twice

Reported by: andremiguelcruz@msn.com Owned by:
Priority: low Milestone: None
Component: event Version: 1.8.0
Keywords: Cc:
Blocked by: Blocking:
Description

Attaching focus/blur with delegation using a * selector causes handlers to be fired twice on input elements that are within a form.

See: http://jsfiddle.net/fNEhG/1/

Attachments (0)
Change History (6)

Changed August 02, 2012 07:39PM UTC by anonymous comment:1

On the fiddle, the first event has currentTarget equal to the element and the second has currentTarget equal to the form.

So the event is bubbling to the form, but shouldn't this be handled in the core? Only one element can have focus at the same time, so it doesn't make much sense to fire one for the input and one for the form.

Changed August 02, 2012 09:02PM UTC by anonymous comment:2

Actually, the event is fired for each DOM up in the tree..

Changed August 14, 2012 12:48PM UTC by sindresorhus comment:3

component: unfiledevent
priority: undecidedlow
version: 1.7.21.8.0

I don't see any reason why you can't just do: $(document.body).on('focus', 'input') or even better $('form').on('focus', 'input').

Changed August 14, 2012 09:15PM UTC by andremiguelcruz@msn.com comment:4

Mainly because elements other then form inputs that can have the focus and blur events (e.g. elements with tabIndex defined)

Changed August 15, 2012 10:00AM UTC by sindresorhus comment:5

You could do: $('form').on('focus', 'input, [tabIndex]')

Changed August 15, 2012 01:17PM UTC by dmethvin comment:6

resolution: → worksforme
status: newclosed

This is working correctly as far as I can tell. Delegated events only work with bubbling event types. The focus and blur events are not defined to bubble by the W3C, so **as a convenience** we translate them to focusin and focusout. There is no other special handling done for focus and blur.

As the event bubbles up from the input, jQuery compares each element to the selector and fires the handler on the element if there is a match. Since * matches everything, each element up the line gets its turn with the handler.

The effect is easier to see with a deeper tree: http://jsfiddle.net/dmethvin/fNEhG/4/

Or to avoid the red herring about the focus event, here's one with click: http://jsfiddle.net/dmethvin/fNEhG/5/