jQuery idleTimer plugin
jQuery idleTimer plugin
There are a few cases where you want to know if the user is idle. Namely:
- You want to preload more assets
- You want to grab their attention to pull them back
- You want close their banking session after 5 minutes of inactivity.(Jerk!)
- You want the site to sneak off the screen and see if they notice ;-)
Nick Zakas wrote a script for YUI3 to handle these cases. His writeup has a great description of the architecture approach he took to the script.
In my jQuery adaptation, I did a few different things:
- Leveraged event namespaces for easy unbinding
- Considered mousewheel as activity, in addition to keyboard and mouse movement.
- Gave it a bit more jQuery-ish of an API
To use:
// idleTimer() takes an optional argument that defines the idle timeout // timeout is in milliseconds; defaults to 30000 $.idleTimer(10000); $(document).bind("idle.idleTimer", function(){ // function you want to fire when the user goes idle }); $(document).bind("active.idleTimer", function(){ // function you want to fire when the user becomes active again }); // pass the string 'destroy' to stop the timer $.idleTimer('destroy'); Get the source on github (4.6k unminified) View the demo Note: If you want to change the timeout interval, you'll have to destroy the existing timer first. 2009.09.22: I've updated the idleTimer script for a few more features… // you can query if the user is idle or not with data() $.data(document,'idleTimer'); // 'idle' or 'active' // you can get time elapsed since user when idle/active $.idleTimer('getElapsedTime'); // time since state change in ms You can get the latest code, naturally, on github. 2010.05.11: Due to popular demand, there is now support for multiple timers!! Why would you want this? Lets say you want .. One Timer to restore the forms, messages boxes, etc. Another Timer of a different length timeout to notify about expiration sessions. // bind to specific elements, allows for multiple timer instances $(elem).idleTimer(30*1000); $(elem).idleTimer('destroy'); $(elem).idleTimer('getElapsedTime'); // some ms something $.data(elem,'idleTimer'); // 'idle' or 'active'
|
Notice this new API is on $.fn.idleTimer, as in it works on a jQuery collection instead of just the jQuery global object.
If you're using this along with the old $.idleTimer api, you should not do$(document).idleTimer(...)
All these element-bound timers will only watch for events inside of them. You may just want to watch page-level activity, in which case you may set up your timers ondocument,document.documentElement, anddocument.body. Those will allow three separate timers that will catch all page activity.
Again, check out the demo or view the source on github. :)
2011.03.11 : You should check out Eric Hynds' Idle Timeout plugin. It improves a good bit on this guy here.
Dowload : idle package