Javascript/Jquery: Test If Window Has Focus

JavaScript / jQuery: Test if window has focus

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

Check if window has focus

var has_focus = true;

function loading_time() {
$(":focus").each(function() {
if($(this).attr("id")=="iframeID") has_focus = true;
});

if(has_focus==true) alert('page has focus');
else alert('page has not focus');

setTimeout("loading_time()", 2000);
}

window.onblur = function(){
has_focus=false;
}
window.onfocus = function(){
has_focus=true;
}

$(window).load(function(){
setTimeout("loading_time()", 2000);
});

To make it more efficient, you need to var has_focus = false; and make the user click somewhere on the page.

javascript how check if browser got focus

Simply, you can check whether window is on focus or not by using native javascript event handler. we will use window.onblur to check if window isn't on focus and use window.onfocus to check if window is on focus.

    window.onblur = function(){
// do some event handler here...in your case, to show new message alert on the title if the user receive new message.
newMessageChecker();
}
window.onfocus = function(){
// invoke another function to bring back your default title and destroy the Interval you have created.
destroyMessageChecker();
}
function newMessageChecker(){
// check if the user have new message. you may use setInterval method
window.messageChecker = setInterval(function(){
// if true, do some stuff like this
document.title = "New Message("+ messageCount +") : " + yourDefaultTitleValue;
}, 3000);
}
function destroyMessageChecker(){
// change your title to default value
document.title = yourDefaultTitleValue;
clearInterval(window.messageChecker);
}

for more information about window event, please take a look at this link Window Event Attributes. if you prefer to use jQuery please check this page Using jQuery to bind “focus” and “blur” functions for “window”

Using jQuery to test if an input has focus

jQuery 1.6+

jQuery added a :focus selector so we no longer need to add it ourselves. Just use $("..").is(":focus")

jQuery 1.5 and below

Edit: As times change, we find better methods for testing focus, the new favorite is this gist from Ben Alman:

jQuery.expr[':'].focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};

Quoted from Mathias Bynens here:

Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.

You're defining a new selector. See Plugins/Authoring. Then you can do:

if ($("...").is(":focus")) {
...
}

or:

$("input:focus").doStuff();

Any jQuery

If you just want to figure out which element has focus, you can use

$(document.activeElement)

If you aren't sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing:

(function ( $ ) {
var filters = $.expr[":"];
if ( !filters.focus ) {
filters.focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
}
})( jQuery );

Is there a way to detect if a browser window is not currently active?

Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.

document.addEventListener("visibilitychange", onchange);

Current browser support:

  • Chrome 13+
  • Internet Explorer 10+
  • Firefox 10+
  • Opera 12.10+ [read notes]

The following code falls back to the less reliable blur/focus method in incompatible browsers:

(function() {
var hidden = "hidden";

// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;

function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};

evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}

// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();

onfocusin and onfocusout are required for IE 9 and lower, while all others make use of onfocus and onblur, except for iOS, which uses onpageshow and onpagehide.

Check if windows/page/document/iframe has focus

var has_focus = true;

function loading_time() {
$(":focus").each(function() {
if($(this).attr("id")=="iframeID") has_focus = true;
});

if(has_focus==true) alert('page has focus');
else alert('page has not focus');

setTimeout("loading_time()", 2000);
}

window.onblur = function(){
has_focus=false;
}
window.onfocus = function(){
has_focus=true;
}

$(window).load(function(){
setTimeout("loading_time()", 2000);
});

To make it more efficient, you need to var has_focus = false; and make the user click somewhere on the page.

Is there a 'has focus' in JavaScript (or jQuery)?

There is no native solution but yes there is a more elegant way you can do it:

jQuery.extend(jQuery.expr[':'], {
focus: "a == document.activeElement"
});

You're defining a new selector. See Plugins/Authoring. Then you can do:

if ($("...").is(":focus")) {
...
}

or:

$("input:focus").doStuff();


Related Topics



Leave a reply



Submit