83

How do you test if the browser has focus?

3
  • See also stackoverflow.com/questions/483741/… which can answer this question as well. Jun 29, 2011 at 15:12
  • 15
    Try document.hasFocus(), which returns a boolean. It's built into the spec, so it can be done without jQuery. Feb 4, 2013 at 21:41
  • For someone who want check pages' visibility (which is not as same as focus), please checkout Page Visibility API for more details.
    – tsh
    Apr 19, 2018 at 10:08

4 Answers 4

163

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

EDIT: Added fiddle http://jsfiddle.net/Msjyv/3/

HTML

Currently <b id="status">without</b> focus...

JS

function check()
{
    if(document.hasFocus() == lastFocusStatus) return;

    lastFocusStatus = !lastFocusStatus;
    statusEl.innerText = lastFocusStatus ? 'with' : 'without';
}

window.statusEl = document.getElementById('status');
window.lastFocusStatus = document.hasFocus();

check();
setInterval(check, 200);
11
  • 3
    I tried the example from the above link and it worked well in IE7+, Chrome, and FF4. +1 for you. May 3, 2011 at 14:56
  • 1
    Great little function, works much better than other jQuery equivalents I have run across.
    – Heath
    Aug 31, 2011 at 20:10
  • 3
    More useful than the accepted answer, I had problems with the timer loading while the window was out of focus.
    – Kokos
    Oct 17, 2011 at 14:06
  • This is not supported by Opera. The calming fact is that they are in process of switching the rendering engine to Webkit :) Feb 25, 2013 at 8:38
  • 6
    In the meantime you can use some thing like this to get the functionality in Opera: if(typeof document.hasFocus === 'undefined') { document.hasFocus = function () { return document.visibilityState == 'visible'; } }
    – Kent
    Apr 2, 2013 at 9:37
79

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);
});​
7
  • @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?
    – user113716
    Aug 13, 2010 at 19:39
  • Chrome actually. After further testing, my first comment might be wrong - the tab key breaking it seems to be more consistent.
    – jball
    Aug 13, 2010 at 19:40
  • @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.
    – user113716
    Aug 13, 2010 at 19:42
  • 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.
    – user113716
    Aug 13, 2010 at 19:45
  • 4
    Use window.top to check the topmost window. Jun 17, 2011 at 15:26
3

Simple javascript snippet

Event based:

function focuschange(fclass) {
    var elems=['textOut','textFocus'];
    for (var i=0;i<elems.length;i++) {
        document.getElementById(elems[i]).
            setAttribute('class',fclass);
    }
}
window.addEventListener("blur",function(){focuschange('havnt')});
window.addEventListener("focus",function(){focuschange('have')});
focuschange('havnt');
.have                { background:#CFC; }
#textOut.have:after  { content:'';      }
.havnt               { background:#FCC; }
#textOut.havnt:after { content:' not';  }
<span id='textOut'>Have</span><span id='textFocus'> focus</span>

Interval pool based:

setInterval(function() {
    var fclass='havnt';
    if (document.hasFocus()) {
      fclass='have';
    };
    var elems=['textOut','textFocus'];
    for (var i=0;i<elems.length;i++) {
        document.getElementById(elems[i]).
            setAttribute('class',fclass);
    }
},100);
#textOut.have:after  { content:'';     }
#textOut.havnt:after { content:' not'; }
.have  { background:#CFC; }
.havnt { background:#FCC; }
<span id='textOut'>Have</span><span id='textFocus'> focus</span>

1
  • I like this answer because of the event based solution. Imho, it should be the prefered way always.
    – quasi
    Sep 12, 2020 at 11:56
1

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

1
  • Apparently blur doesn't fire when when switching tabs. :( Nov 12, 2013 at 20:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.