views:

1190

answers:

2

I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it'd be nice to not run.

Is there a way to do this using JavaScript?

My reference point: GMail Chat plays a sound if the window you're using isn't active.

+7  A: 

You can detect when the browser window loses and gains focus and set a variable accordingly. IE's behavior differs slightly from other browsers. See the following page:

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

Andy E
Excellent, that's just what I was looking for but apparently wasn't using the right search terms to find. I tried (using jQuery) $(window).bind('blur', function() { alert("i lost focus") }) which didn't work, but I will go back try again using the link here.
Luke Francl
Perfect... I didn't ever think I needed to do this, until my boss asked me to implement it!
Stephen Orr
A: 

Slightly more complicated way would be to use setInterval() to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.

This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.

Austin Hyde
Unless the user doesn't have a mouse.
grawity
Heaven forbid you sit down to code (no one here does that, right?) or reply to an email, and don't use the mouse.
Roger Pate
related: Going Commando - http://www.codinghorror.com/blog/archives/000825.html
Annan