2

I want to detect if my browser window has a focus on it (is selected). I use the following code to do so:

$(window).focus(function() { 
    window.focusFlag = true; 
}).blur(function() { 
    window.focusFlag = false; 
});

Source: Using JQuery to bind "focus" and "blur" functions for "window", doesn't work in IE

It works on mozilla firefox 43.0.4, but it doesn't work on IE 11.

I also tried focus/blur method which does not involve JQuery.

function onBlur() {
    document.body.className = 'blurred';
};
function onFocus(){
    document.body.className = 'focused';
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

It also works on mozilla firefox 43.0.4, but it doesn't work on IE 11.

Srource: http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

What can I do about IE 11?

Community
  • 1
  • 1
Benas
  • 2,106
  • 2
  • 39
  • 66
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API – epascarello Jan 13 '16 at 13:25
  • @epascarello the reason I'm using these outdated methods is that I need to support older browser versions as well. That api is not supported by older browsers :( – Benas Jan 13 '16 at 13:31
  • 1
    So you use that for browsers that support it.... https://github.com/ai/visibilityjs – epascarello Jan 13 '16 at 13:32

1 Answers1

1

The standard defines for focus:

This event type is similar to focusin, but is dispatched after focus is shifted, and does not bubble. https://www.w3.org/TR/uievents/#events-focusevent

Therefore, focusin will work for parents in jQuery.

<input type="text" />

$(window).focusin(function() { alert("Focussed"); }).focusout(function() { alert("Blur"); });

Try in JSFiddle

Andy
  • 4,783
  • 2
  • 26
  • 51
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28