Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing browser tabs undesirably fires the focus event, especially in Google Chrome

I've got a little issue with the focus event that I just became aware of. Apparently, focus fires when switching to another browser tab and then back again. I'd rather not have that happen; is it possible?

I was never aware of this until today. Here's a little demo: http://jsfiddle.net/MJ6qb/1/

var times = 0;
$('input').on('focus', function() {
    times ++;
    $(this).after('<br>Focused '+times+' times');   
});

To reproduce: Focus on the input, then switch browser tabs, then switch back. All browsers seem to fire the focus event when you switch back to the tab, and Google Chrome 19 is firing it twice!

Ideally, the function should not run when switching browser tabs at all but only on user click or Tab, but now that I'm aware of the Chrome issue I'm a bit more concerned about that because it's resulting in extra unwanted back-to-back AJAX requests in my real app (it's for fetching results for an autocomplete that needs to be up to date, but not so much that I want to use the keyup event).

It doesn't seem jQuery related (I did test with vanilla javascript) but I can using jQuery for a solution. Is there anything I can do about this? I know I can use jQuery's one() but I do want the function to run more than once.

like image 541
Wesley Murch Avatar asked May 18 '12 17:05

Wesley Murch


People also ask

How do I change my browser focus from one tablet to another?

Using Javascript, triggering an alert can have the desired effect. Run this code in your console, or add to your html file in one tab and switch to another tab in the same browser. setTimeout(function(){ alert("Switched tabs"); }, 5000);

Why do my Chrome tabs keep changing?

This happens because of a Chrome feature that “discards” any tabs you haven't used for some time, in order to save memory and prevent the browser or even your PC or Mac from running slow.


1 Answers

Try this

var times = 0;
var prevActiveElement;

    $( window ).on( "blur", function(e){
            prevActiveElement = document.activeElement;
    });

    $('input').on('focus', function() {
        if (document.activeElement === prevActiveElement) {
            return;
        }
        prevActiveElement = document.activeElement;
        times++;
        $(this).after('<br>Focused ' + times + ' times');
    }).on( "blur", function(){
        prevActiveElement = null;  
    });​
like image 109
Esailija Avatar answered Sep 18 '22 16:09

Esailija