Skip to content

How to Detect user is active or idle on web page Using JQuery ?

Last updated on December 2, 2022

In this post, I will show you how to Detect user State(active or idle) on the web page or on the element using JQuery.

if you find in some sites (for example Godaddy.com) that the user stays ideal for some time automatically he/she will get an alert, like your idle for this much time on site and your session is going to expire within 5 minutes or something else. We can implement this functionality easily by using JQuery.

Possible events on the webpage.

  • Mouse Moves, Mouse Wheel or Mouse Scrolls, Mouse Down or Mouse up, Click
  • Keyboard button presses (press down or up)

Based on the above events we can analyze the user state, if a user doesn’t do any above actions he/she is idle or inactive.

Here is the Jquery Events list which I am using in the tutorial.

  • mousemove
  • click
  • mouseup
  • mousedown
  • keydown
  • keypress
  • keyup
  • submit
  • change
  • mouseenter
  • scroll
  • resize
  • dblclick

Here is the sample script

   $(document).ready(function () {
		var idleState = false;
		var idleTimer = null;
        $('*').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
            clearTimeout(idleTimer);
            if (idleState == true) { 
                $("body").css('background-color','#fff');            
            }
            idleState = false;
            idleTimer = setTimeout(function () { 
				$("body").css('background-color','#000');
                idleState = true; }, 2000);
        });
        $("body").trigger("mousemove");
    });

The logic is here very simple we bind events(listed above) to all elements, and on DOM Ready mouse move events triggering(on page load).

If we user performs any above events, we postpone the idle event for the next 2 seconds.

If he doesn’t do anything for 2 seconds the anonymous function is automatically called by the timer event. Here is the example we are changing the background color to black. if the user does any of the above events background color changes to white.

That’s all for today, I hope you liked this tutorial please feel free to comment with your feedback and suggestion.

4.5 4 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments