views:

65

answers:

3

Hi all,

How do you test if the browser has focus?

Thanks,

rod.

+3  A: 

I haven't tested this in other browsers, but it seems to work in Webkit. I'll let you try IE. :o)

Try it out: http://jsfiddle.net/ScKbk/

After you click to start the interval, change the focus of the browser window to see the result change. Again, tested only in Webkit.

var window_focus;

$(window).focus(function() {
    window_focus = true;
})
    .blur(function() {
        window_focus = false;
    });

$(document).one('click',function() {
   setInterval(function() { $('body').append('has focus? ' + window_focus + '<br>'); }, 1000);
});​
patrick dw
@jball - Must be IE? In Webkit and Firefox any activation of the window triggers the focus. I wonder if there's a workaround for IE. Also, did you test on your page? Maybe there an issue because the jsFiddle uses frames?
patrick dw
Also, pressing the tab key seems to break it permanently.
jball
Chrome actually. After further testing, my first comment might be wrong - the tab key breaking it seems to be more consistent.
jball
@jball - I'm guessing that the tab key breaks it because jsFiddle has lots of input elements in other frames. Get rid of the frames, and I'll bet it will work a little better for you.
patrick dw
Works mostly in IE.
jball
I believe each frame has its own `window` object, so if you were to use frames, you would probably just need to include the script in each one.
patrick dw
A: 

Hi, use the hasFocus method of the document. You can find detailed description and an example here: hasFocus method

gumape
A: 

HTML:

<button id="clear">clear log</button>
<div id="event"></div>​

Javascript:

$(function(){

    $hasFocus = false;

    $('#clear').bind('click', function() { $('#event').empty(); });

    $(window)
        .bind('focus', function(ev){
            $hasFocus = true;
            $('#event').append('<div>'+(new Date()).getTime()+' focus</div>');
        })
        .bind('blur', function(ev){
            $hasFocus = false;
            $('#event').append('<div>'+(new Date()).getTime()+' blur</div>');
        })
        .trigger('focus');

    setInterval(function() {
        $('#event').append('<div>'+(new Date()).getTime()+' has focus '+($hasFocus ? 'yes' : 'no')+'</div>');
    }, 1000);
});​

test

UPDATE:

I'll fix it, but IE does not work very well

test update

andres descalzo
Doesn't consistently work in IE8 in my testing.
Nicholas H