Fire Event When User is Idle

Avatar of Chris Coyier
Chris Coyier on

See the two commented lines below, that is where you can insert code for things to do when the user goes idle, and when the user comes back. Set the idle period on the third line, 1000 = 1 second.

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {
        $('*').bind('mousemove keydown scroll', function () {
            if (idleState == true) { 
                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");            
            idleState = false;
            idleTimer = setTimeout(function () { 
                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

                idleState = true; }, idleWait);
}) (jQuery)

This works by using a setTimeout function to fire at the end of the specified seconds. If basically anything happens during that time (the mouse moves, the page is scrolled, or a key is pressed) the timeout period is reset.