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);
});
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);
});
Share
Improve this question
edited Nov 9, 2015 at 12:32
Anders
8,65310 gold badges60 silver badges99 bronze badges
asked May 14, 2012 at 10:06
heiningairheiningair
4511 gold badge6 silver badges23 bronze badges
3 Answers
Reset to default 4I 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.
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 remend 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.
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();
});