How can I detect with JavaScript/jQuery if the user is currently active on the page?

I am needing to detect when a user is inactive (not clicking or typing) on the current page for more than 30 minutes.

I thinking it might be best to use event blubbling attached to the body tag and then just keep resetting a timer for 30 minutes, but I'm not exactly sure how to create this.

I have jQuery available, although I'm not sure how much of this will actually use jQuery.

Edit: I'm more needing to know if they are actively using the site, therefore clicking (changing fields or position within a field or selecting checkboxes/radios) or typing (in an input, textarea, etc). If they are in another tab or using another program, then my assumption is they are not using the site and therefore should be logged out (for security reasons).

Edit #2: So everyone is clear, this is not at all for determining if the user is logged in, authenticated or anything. Right now the server will log the user out if they don't make a page request within 30 minutes. This functionality to prevent the times when someone spends >30 minutes filling in a form and then submitting the form only to find out that they haven't been logged out. Therefore, this will be used in combination with the server site to determine if the user is inactive (not clicking or typing). Basically, the deal is that after 25 minutes of idle, they will be presented with a dialog to enter their password. If they don't within 5 minutes, the system automatically logs them out as well as the server's session is logged out (next time a page is accessed, as with most sites).

The Javascript is only used as a warning to user. If JavaScript is disabled, then they won't get the warning and (along with most of the site not working) they will be logged out next time they request a new page.



You can watch mouse movement, but that's about the best you're going to get for indication of a user still being there without listening to the click event. But there is no way for javascript to tell if it is the active tab or if the browser is even open. (well, you could get the width and height of the browser and that'd tell you if it was minimized)


I just recently did something like this, albeit using Prototype instead of JQuery, but I imagine the implementation would be roughly the same as long as JQuery supports custom events.

In a nutshell, IdleMonitor is a class that observes mouse and keyboard events (adjust accordingly for your needs). Every 30 seconds it resets the timer and broadcasts an state:idle event, unless it gets a mouse/key event, in which case it broadcasts a state:active event.

var IdleMonitor = Class.create({

    debug: false,
    idleInterval: 30000, // idle interval, in milliseconds
    active: null,
    initialize: function() {
        document.observe("mousemove", this.sendActiveSignal.bind(this));
        document.observe("keypress", this.sendActiveSignal.bind(this));
        this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);

    // use this to override the default idleInterval
    useInterval: function(ii) {
        this.idleInterval = ii;
        this.timer = setTimeout(this.sendIdleSignal.bind(this), ii);

    sendIdleSignal: function(args) {
        // console.log("state:idle");'state:idle'); = false;

    sendActiveSignal: function() {
            // console.log("state:active");
   = true;
            this.timer = setTimeout(this.sendIdleSignal.bind(this), this.idleInterval);

Then I just created another class that has the following somewhere in it:

Event.observe(document, 'state:idle', your-on-idle-functionality);
Event.observe(document, 'state:active', your-on-active-functionality)

Using jQuery, you can easily watch mouse movement, and use it to set a variable indicating activity to true, then using vanilla javascript, you can check this variable every 30 minutes (or any other interval) to see if its true. If it's false, run your function or whatever. Look up setTimeout and setInterval for doing the timing. You'll also probably have to run a function every minute or so to reset the variable to false.


Here my shot:

var lastActivityDateTime = null;

function checkActivity( )
    var currentTime = new Date();
    var diff = (lastActivityDateTime.getTime( ) - currentTime.getTime( ));
    if ( diff >= 30*60*1000)
        //user wasn't active;
    setTimeout( 30*60*1000-diff, checkActivity);

setTimeout( 30*60*1000, checkActivity); // for first time we setup for 30 min.

// for each event define handler and inside update global timer
$( "body").live( "event_you_want_to_track", handler);

function handler()
   lastActivityDateTime = new Date();
   // rest of your code if needed.

If it's a security issue, doing this clientside with javascript is absolutely the wrong end of the pipe to be performing this check. The user could easily have javascript disabled: what does your application do then? What if the user closes their browser before the timeout. do they ever get logged out?

Most serverside frameworks have some kind of session timeout setting for logins. Just use that and save yourself the engineering work.

You can't rely on the assumption that people cannot log in without javascript, therefore the user has javascript. Such an assumption is no deterrent to any determined, or even modestly educated attacker.

Using javascript for this is like a security guard handing customers the key to the bank vault. The only way it works is on faith.

Please believe me when I say that using javascript in this way (and requiring javascript for logins!!) is an incredibly thick skulled way to engineer any kind of web app.


Without using JS, a simpler (and safer) way would simply be to have a lastActivity timestamp stored with the user's session and checking it on page load. Assuming you are using PHP (you can easily redo this code for another platform):

if(($_SESSION['lastAct'] + 1800) < time()) {
    header('Location: session_timeout_message.php');

$_SESSION['lastAct'] = time();

and add this in your page (optional, the user will be logged out regardless of if the page is refreshed or not (as he logs out on next page log)).

<meta http-equiv="refresh" content="1801;" /> 

If your concern is the lost of information for the user after a login timeout; another option would be to simply store all the posted information upon the opening of a new session (a new session will always be started when the older session has been closed/scrapped by the server) when the request to a page is made before re-routing to the logging page. If the user successfully login, then you can use this saved information to return the user back to where he was. This way, even if the user walk away a few hours, he can always return back to where he was after a successful login; without losing any information.

This require more work by the programmer but it's a great feature totally appreciated by the users. They especially appreciate the fact that they can fully concentrate about what they have to do without stressing out about potentially losing their information every 30 minutes or so.


This is what I've come up with. It seems to work in most browsers, but I want to be sure it will work everywhere, all the time:

var timeoutTime = 1800000;
var timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);
$(document).ready(function() {
    $('body').bind('mousedown keydown', function(event) {
        timeoutTimer = setTimeout(ShowTimeOutWarning, timeoutTime);

Anyone see any problems?


Ifvisible.js is a crossbrowser lightweight solution that does just that. It can detect when the user switches to another tab and back to the current tab. It can also detect when the user goes idle and becomes active again. It's pretty flexible.


Ifvisible is a nice JS lib to check user inactivity.

ifvisible.setIdleDuration(120); // Page will become idle after 120 seconds

ifvisible.on("idle", function(){
   // do something


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.