Hi all,
How do you test if the browser has focus?
Thanks,
rod.
Hi all,
How do you test if the browser has focus?
Thanks,
rod.
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);
});
Hi, use the hasFocus method of the document. You can find detailed description and an example here: hasFocus method
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