0

I have an counter on my site and I want this to pause when my site isnt focused. If I use the blur (someone leaves the focus) and someone clicks on a link that opens in a new tab and then closes the tab the focus isn't back on the previous page? Why doesnt it work? Is there a better way to do it?

$(document).blur(function(){
    pause=true;
});

$(document).focus(function(){
    //alert("test");
    pause=false;

    countdown(tmp,msg);
});
Anders
  • 8,307
  • 9
  • 56
  • 88
heiningair
  • 441
  • 1
  • 6
  • 23

3 Answers3

4

I think it's not attached to document, but on window

$(window).focus(function(){...});
$(window).blur(function(){...});

The ones that I always encounter are the native JS versions window.onfocus and window.onblur. I suppose these are also used/abstracted in jQuery as well.

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • You're right. [MDN link](https://developer.mozilla.org/en/DOM/window.onblur), for example. – Sirko May 14 '12 at 10:08
  • but even if I use window.. it doesnt get the focus back after closing the new tab?! – heiningair May 14 '12 at 10:14
  • I don't know if it's a browser security measure, but in [this example](http://jsfiddle.net/hBVuX/embedded/result/), focus is achieved when you click the page (and alerts infinitely in Chrome). – Joseph May 14 '12 at 10:21
  • still not working.. I tried your code but it doesnt work (chrome + firefox)! It works on changing the focus but not on closing tabs.. – heiningair May 14 '12 at 10:24
0

Essentially you don't gain focus until someone clicks or tabs into the page, that's just how focus works. Working code below :-

 $(function() {

    $(window).focus(function() {
        alert("in");
    });
     $(window).blur(function() {
        alert("out");
    });

});

You could add window mouse in/out events however I wouldn't recommend this as touch devices won't be supported and people using multiple screens will have issues.

Your problem is more of a software one rather than a JS issue. In this case you are at the mercy of the browser, although you go back to the tab you want you are still in blur state until you click in the window itself.

abarisone
  • 3,707
  • 11
  • 35
  • 54
M T
  • 136
  • 1
  • 8
0

Can manage with 'click' and outside click with below code

$(document).click(function() {
    //hide
});
$(document).keyup(function(e) {
    //manage tab event 
    if (e.target.id == "idName") {
        //show
    } else {
        //hide
    }
});

$(#idName).bind('click', function(e) {
    //show 
    e.stopPropagation();
});