JavaScript / jQuery: Test if window has focus
How do you test if the browser has focus?
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);
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);
});
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>
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