4

Is It possible to detect when browser window Is active/inactive

I did try:

$(window).on('focus', function(){
    console.log(1);
});
$(window).on('blur', function(){    
    console.log(2);    
});

But it seems that it's working only when user will click the window. but showing 2 when user will click eg. browser address bar.

What I want to achieve is to detect when current tab is active one.

How to improve this code?

LJ Wadowski
  • 6,424
  • 11
  • 43
  • 76
  • You can't check that. What you can check is if the user moves his mouse over the tab (but the tab could also be active but the mouse is somewhere else). – hffmr Oct 19 '14 at 15:01
  • 3
    Modern browsers have a page visibility API: http://caniuse.com/#search=page visibility – Mottie Oct 19 '14 at 15:06

1 Answers1

3

Active means when the tab is visible. But if you want to tell if the user's mouse is directly on the page, you could use this:

<html onmouseenter="document.getElementById('h1').innerHTML = 'active'"onmouseleave="document.getElementById('h1').innerHTML = 'not active'">
  <body style="width:100%;height:100px">
    <h1 id="h1">not active</h1>
  </body>
</html>
With the simple code above you can tell if the users mouse is on the page or not

EDIT: using the page visibility API:

var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
    visibilityChange = "visibilitychange";
} 
else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
    visibilityChange = "mozvisibilitychange";
} 
else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
} 
else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
}

function handleVisibilityChange() {
    if (document[hidden]) {
        //Not visible, Do whatever
    }
    else {
        //Visible
    }
}

if (typeof document.addEventListener === "undefined" ||
    typeof document[hidden] === "undefined") {
    alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} 
else {
    document.addEventListener(visibilityChange, handleVisibilityChange, false);
DividedByZero
  • 4,333
  • 2
  • 19
  • 33