$ (window) .focus () is executed twice for each focus

I am not sure why this is happening, and I would like an explanation.

Using the jquery focus method, I snap to the window focus event. This is a working example (copy to html file and open it in a browser. For some reason, it does not work in jsfiddle or jsbin)

 <!DOCTYPE html> <html> <head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script></head> <body> <p1>Here:</p1> <div id="here" >Why</div> </body> <script> $(window).load(function() { $(window).focus(function() {console.log("focus");}); $(window).blur(function() {console.log("blur");}); }); </script> </html> 

When the browser regains focus, the function runs twice, and the "focus" is printed twice in the console. Any idea why this is happening?

The ultimate goal, by the way, is to stop the timer from starting when the user leaves the browser in an application or other tab.

UPDATE

Works on the latest (dev) version of chrome. I will check it on firefox and write if it is different there.

UPDATE 2 Interesting fact - does not happen in firefox. Perhaps this is a mistake with chrome.

+4
source share
5 answers

I had the same problem. My fix for this was to use the lodash debounce() function ( https://lodash.com/docs/#debounce ). This was my fix:

 var debouncedFocus = _.debounce(() => { console.log('focussed'); }, 250, {leading: true, trailing: false}); $(window).on('focus', debouncedFocus); 
0
source

live () is deprecated. Use on () instead.

 $(window).on("focus", function(){ alert("focus!"); }); 

You can try using the live () function.

$ (window) .live ("focus", function () {alert ("focus!");});

+1
source

Maybe load() is called twice? You can register these events without .load() . Try the following:

 <script> $(window).focus(function() {console.log("focus");}); $(window).blur(function() {console.log("blur");}); </script> 
0
source

Which browser? Everything seems to be in order.

As a precaution, you can use the javascript variable so that it runs only once.

 <script> var isFocused = false; $(window).load(function() { $(window).focus(function() { if(isFocused) return; console.log("focus"); isFocused = true; }); $(window).blur(function() { console.log("blur"); isFocused = false; }); }); </script> 
0
source

If you are using Underscore at the same time, you can use the _.debounce() method to compress recurring events in a single event.

0
source

All Articles