JavaScript / jQuery: Test if window has focus

JavascriptJqueryEvents

Javascript Problem Overview


How do you test if the browser has focus?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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);
});​

Solution 3 - Javascript

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>

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRodView Question on Stackoverflow
Solution 1 - JavascriptgumapeView Answer on Stackoverflow
Solution 2 - Javascriptuser113716View Answer on Stackoverflow
Solution 3 - JavascriptF. HauriView Answer on Stackoverflow
Solution 4 - Javascriptandres descalzoView Answer on Stackoverflow