How To Detect Active Users On Your Web Page Using JavaScript

In this tutorial, you will learn how to detect user activity on your website using JavaScript. By monitoring mouse movements, key presses, and window focus events, you can determine if a user is actively engaging with your webpage. This functionality is essential for improving user experience, maintaining session security, and enhancing interactive features on your site.

We'll walk you through setting up event listeners and implementing a function that checks for user activity status, ensuring your website can dynamically respond to user behavior.

To detect if a user is currently active on your webpage by tracking mouse movement, key presses, and window focus, you can create a JavaScript function that sets up event listeners for these actions.

User Activity Detection JavaScript Function

This JavaScript function, checkUserActivity(), checks the time difference between the current time and the last active time.

If the time difference is greater than 30 seconds (indicating inactivity), it sets user_active to false and logs "User is inactive" to the console.

Otherwise, it sets user_active to true and logs "User is active" to the console

You can adjust the inactivity threshold (currently set to 30 seconds) and the check interval (currently set to 5 seconds) as per your requirements.

javaScript
const UserActivityDetector = (() => {
    let user_active = false;
    let user_last_active_time = new Date();

    const inactivity_threshold_seconds = 30;
    const check_interval_ms = 5000; // millisecond

    // Debounced function to update user activity status
    const updateUserActivity = (() => {
        let timeout;
        return () => {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                user_active = true;
                user_last_active_time = new Date();
                logActivity('User is active');
            }, 100);
        };
    })();

    const logActivity = (message) => {
        console.log(message);
    };

    const checkUserActivity = () => {
        const current_time = new Date();
        // Time difference in seconds
        const time_difference = (current_time - user_last_active_time) / 1000;
        // Assuming 30 seconds of inactivity
        if (time_difference > inactivity_threshold_seconds) {
            user_active = false;
            logActivity('User is inactive');
        } else {
            user_active = true;
            logActivity('User is active');
        }
    };

    // Add event listeners to detect user activity
    const activity_events = ["mousedown", "mousemove", "keydown", "scroll", "touchstart"];
    activity_events.forEach(event => {
        document.addEventListener(event, updateUserActivity, true);
    });

    // check user activity status every 5 seconds
    setInterval(checkUserActivity, check_interval_ms);

    // Public API
    return {
        isUserActive: () => user_active,
        LastActiveTime: () => user_last_active_time,
    };
})();

Usage User Activity Detector

javaScript
// Example usage:
UserActivityDetector.isUserActive();
// return boolean true or false

Global usage outside the script

Use the setInterval function outside the script to check user activity periodically. This allows continuous monitoring users active.

javaScript
const userActivityMonitor = () => {
    const status = document.getElementById("user-status");
    const user_active = UserActivityDetector.isUserActive();
    if (user_active) {
        status.innerHTML = "Active";
    } else {
        status.innerHTML = "Inactive";
    }
};
// check every 1 second user active or not
setInterval(userActivityMonitor, 1000);
HTML
<p> Wait 30 seconds, don't move the mouse, click and scroll. View the users active or inactive status text </p>
<div> Current status : <span id="user-status">Inactive</span></div>

Try it yourself edit and preview live

Try it your self