SleepMachine
SleepMachine

Reputation: 23

jQuery event triggers twice

Can someone explain to me why this event triggers twice? It doesn't seem to do it on jQuery versions prior to 1.7.

<input type="textbox" id="box" onblur="console.log('This will trigger twice!');"/>
<script>
$('#box').blur();
</script>

Fiddle: http://jsfiddle.net/EWbmD/52/

Upvotes: 2

Views: 6652

Answers (3)

loveNoHate
loveNoHate

Reputation: 1547

Edit: This might be a solution to your problem.

JSFIDDLE http://jsfiddle.net/SvqwF/7/

Based on focusout.


You trigger it twice, because the .blur() is trigger to

.on('blur focusout', function(){}) (Thanks to @Arun P Johny)

which just triggers the event listener you added inline also, if you do not pass a function to .blur(). JSFIDDLE

Since you added a function inline, that function gets triggered twice.

Description: Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. jQuery .blur()

To get more about the method (for old IE .attachEvent) that is involved with jQuery:

To register more than one event listener for the target, call addEventListener() for the same target but with different event types or capture parameters. MDN

Note: I am unsure as to which event to declare in .on(), it seems like all work

The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser "focusin" and "focusout" events that do bubble. When "focus" and "blur" are used to attach delegated event handlers, jQuery maps the names and delivers them as "focusin" and "focusout" respectively. jQuery .on()

Note 2: blur() <- empty is a shortcut for trigger('blur'). JSFIDDLE

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

From the internals, it looks like triggering blur event is triggering blur and focusout events internally which is invoking the onblur twice.

PoC

$('#box').on('blur focusout', function (e) {
    console.log('this too', e.type);
});
$('#box').blur();

Demo: Fiddle

The blur event is a non bubbling event, the bubbling counterpart is the foucsout event. So in normal circumstances the blur operation triggers both these events. So jQuery is trying to be intelligent and fires both these events in case of a blur event, but it looks like there is an bug in the implementation.

Upvotes: 5

Felix
Felix

Reputation: 38102

You just need to call it once:

$('#box').on('blur', function() {
    console.log('This will trigger twice!');
});

$('#box').blur();

Updated Fiddle

or just remove your jQuery code and keep your onblur event inside your input tag.

Upvotes: -1

Related Questions