dyaa dyaa - 1 year ago 67
jQuery Question

How can i fire an event when the user is Idle

How can i fire a JQuery event when the user is gone on idle from the website for a specified time, and reset the timer on mouse move, scroll or on a key press.

Answer Source

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.

Set the idle period on the third line.

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download