Monday, May 20, 2024
170
rated 0 times [  176] [ 6]  / answers: 1 / hits: 16390  / 12 Years ago, sat, march 10, 2012, 12:00:00

Here is an interesting jsfiddle.



In Firefox:




  1. Run the fiddle

  2. Click in text input

  3. Click somewhere else. Should say 1 blurs.

  4. Click in the text input again.

  5. ALT-TAB to another window. Fiddle should now say 2 blurs.



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?


More From » google-chrome

 Answers
1

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/


[#86930] Friday, March 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;