Check if User is Active or Inactive in Browser Using JavaScript

Javascript is a great programming language to learn. You can do many fun things with Javascript. In the web browser, you can dynamically change the HTML dom elements.

In this article, we will go through how to check if a user is active or inactive. In this example, I will check if there are any browser events inserted like mouse move, click event, or scroll event.

There are many usages where user activity is required to check. Mostly It is necessary to log out a user after inactive or popup modal to confirm the user.

Using Javascript

 function inactivityTime() {
        var time;
        
        // events
        window.onload = resetTime;
        window.onclick = resetTime;
        window.onkeypress = resetTime;
        window.ontouchstart = resetTime;
        window.onmousemove = resetTime;
        window.onmousedown = resetTime;
        window.addEventListener('scroll', resetTime, true);

        function alertUser() {
            // do your task here
            alert("User is inactive.");
        }

        function resetTime() {
            clearTimeout(time);
            time = setTimeout(alertUser, 1000 * 10); // 10 seconds
        }

    };

    // run the function
    inactivityTime(); 

 

Using JQuery

 $(document).ready(function () {
        var inactiveTime;
        $('*').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {

            function alertUser() {
                // do your task here
                alert("User is inactive.");
            }
            
            clearTimeout(inactiveTime);

            inactiveTime = setTimeout(alertUser, 1000 * 10); // 10 seconds
        });
        $("body").trigger("mousemove");
    });

 

Read also: How to Get Current User Location Permission in JavaScript

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js