Here is an interesting jsfiddle.
In Firefox:
In Chrome, at step 5, it says "3 blurs". Two separate "blur" events are fired when the whole browser loses focus. This is of interest because it means that it's not safe to assume, in a "blur" handler, that the element actually had focus just before the event was dispatched; that is, that the loss of focus — the transition from "being in focus" to "not being in focus" — is the reason for the event. When two "blur" events are generated, that condition is not satisfied during the handling of the second event, as the element is already not in focus.
So is this just a bug? Is there a way to tell that a "blur" event is bogus?
The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field). Tip: The onblur event is the opposite of the onfocus event. Tip: The onblur event is similar to the onfocusout event.
If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.
blur( [eventData ], handler ) An object containing data that will be passed to the event handler. A function to execute each time the event is triggered.
The reason it is firing twice is because of window.onblur. The window blurring triggers a blur event on all elements in that window as part of the way javascript's capturing/bubbling process. All you need to do is test the event target for being the window.
var blurCount = 0; var isTargetWindow = false; $(window).blur(function(e){ console.log(e.target); isTargetWindow = true; }); $(window).focus(function(){ isTargetWindow = false; }); $('input').blur(function(e) { if(!isTargetWindow){ $('div').text(++blurCount + ' blurs'); } console.log(e.target); });
http://jsfiddle.net/pDYsM/4/
This is confirmed Chrome bug. See the Chromium Issue Tracker
The workaround is in the accepted answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With