How do you test if the browser has focus?
4 Answers
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);
-
3I 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
-
1Great little function, works much better than other jQuery equivalents I have run across.– HeathAug 31, 2011 at 20:10
-
3More useful than the accepted answer, I had problems with the timer loading while the window was out of focus.– KokosOct 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
-
6In 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'; } }
– KentApr 2, 2013 at 9:37
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);
});
-
@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? 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.– jballAug 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. 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. Aug 13, 2010 at 19:45 -
4
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>
-
I like this answer because of the event based solution. Imho, it should be the prefered way always.– quasiSep 12, 2020 at 11:56
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);
});
UPDATE:
I'll fix it, but IE does not work very well
document.hasFocus()
, which returns a boolean. It's built into the spec, so it can be done without jQuery.